Using default file name (content_disposition) when loading with CURL

I am trying to download some files with PHP and CURL, but I don’t see an easy way to use the default file name (which is in the HTTP response header as

Content-Disposition: attachment; file name = foo.png

) Is there an easier way to get the full title, parse the file name and rename?

+3
source share
3 answers
<?php
$targetPath = '/tmp/';
$filename = $targetPath . 'tmpfile';
$headerBuff = fopen('/tmp/headers', 'w+');
$fileTarget = fopen($filename, 'w');

$ch = curl_init('http://www.example.com/');
curl_setopt($ch, CURLOPT_WRITEHEADER, $headerBuff);
curl_setopt($ch, CURLOPT_FILE, $fileTarget);
curl_exec($ch);

if(!curl_errno($ch)) {
  rewind($headerBuff);
  $headers = stream_get_contents($headerBuff);
  if(preg_match('/Content-Disposition: .*filename=([^ ]+)/', $headers, $matches)) {
    rename($filename, $targetPath . $matches[1]);
  }
}
curl_close($ch);

At first I tried using php: // memory instead /tmp/headers, because using temporary files for this kind of thing is messy, but for some reason I couldn’t get this to work. But at least you understood that ...

CURLOPT_HEADERFUNCTION

+10

, url_fopen .

$response_headers = get_headers($url,1); 
// first take filename from url
$filename = basename($url);   

// if Content-Disposition is present and file name is found use this
if(isset($response_headers["Content-Disposition"]))
{
  // this catches filenames between Quotes
  if(preg_match('/.*filename=[\'\"]([^\'\"]+)/', $response_headers["Content-Disposition"], $matches))
  { $filename = $matches[1]; }
  // if filename is not quoted, we take all until the next space
  else if(preg_match("/.*filename=([^ ]+)/", $response_headers["Content-Disposition"], $matches))
  { $filename = $matches[1]; }
}
// if no Content-Disposition is found use the filename from url


// before using the filename remove all unwanted chars wich are not on a-z e.g. (I the most chars which can be used in filenames, if you like to renove more signs remove them from the 1. parameter in preg_replace
$filename = preg_replace("/[^a-zA-Z0-9_#\(\)\[\]\.+-=]/", "",$filename);

// at last download / copy the content
copy($url, $filename);

: Content-Disposition ( ). preg_match.

+4

Run the HEAD query, match the file name (with regular expressions), and then upload the file.

0
source

All Articles