tags:

views:

113

answers:

2

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?

A: 

Issue an HEAD request, match the filename (with regular expressions) and then download the file.

Alix Axel
Issuing two requests is wasteful. And there's no guarantee that the target actually supports HEAD.
Frank Farmer
+1  A: 
<?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

Frank Farmer