Php – Using the default filename (content_disposition) when downloading with CURL

curlPHP

I'm trying to download some files with PHP & CURL, but I don't see an easy way to use the default suggested filename (which is in the HTTP response header as

Content-Disposition: attachment; filename=foo.png

). Is there an easier way then get the full header, parse the file name and rename?

Best Answer

<?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);

I initially tried to use php://memory instead of /tmp/headers, 'cause using temp files for this sort of thing is sloppy, but for some reason I couldn't get that working. But at least you get the idea...

Alternately, you could use CURLOPT_HEADERFUNCTION