2010-11-03 27 views
1

comment puis-je déterminer le nom du fichier dans l'en-tête quand je reçois avec PHP. verrouiller à ce:Comment puis-je obtenir le nom de fichier de l'en-tête en utilisant curl dans PHP?

<?php 
/* 
This is usefull when you are downloading big files, as it 
will prevent time out of the script : 
*/ 
set_time_limit(0); 
ini_set('display_errors',true);//Just in case we get some errors, let us know.... 

$fp = fopen (dirname(__FILE__) . '/tempfile', 'w+');//This is the file where we save the information 
$ch = curl_init('http://www.example.com/getfile.php?id=4456'); // Here is the file we are downloading 

/* 
    the server get me an header 'Content-Disposition: attachment; filename="myfile.pdf"' 

    i want get 'myfile.pdf' from headers. how can i get it ? 
*/ 

$fileNameFromHeader = '?????????????'; 

curl_setopt($ch, CURLOPT_TIMEOUT, 50); 
curl_setopt($ch, CURLOPT_FILE, $fp); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
curl_exec($ch); 
curl_close($ch); 
fclose($fp); 

// rename file 
rename(dirname(__FILE__) . '/tempfile', dirname(__FILE__) . $fileNameFromHeader); 

Répondre

1

Créer un rappel qui lit les en-têtes et les analyser vous-même. Quelque chose comme:

function readHeader($ch, $header) 
{ 
      global $responseHeaders; 
      $url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); 
      $responseHeaders[$url][] = $header; 
     return strlen($header); 
} 

... curl stuff ... 
// if you need to call a class method use this: 
// curl_setopt($ch, CURLOPT_HEADERFUNCTION, array(&$this,'readHeader')); 
// for a non class method use this 
curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'readHeader'); 
$result = curl_exec($ch); 

// all headers are now in $responseHeaders 
1

Je voudrais utiliser la fonction mentionnée par Byron. Cependant, si vous voulez juste le nomFichierFromHeader, je l'inclurais dans la fonction readHeader:

function readHeader($ch, $header) 
{ 
    global $responseHeaders; 
    $url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); 
    $responseHeaders[$url][] = $header; 

    // $url = 'http://stackoverflow.com/questions/4091203/how-can-i-get-file-name-from-header-using-curl-in-php'; 
    $params = explode('/', $url); 
    $fileNameFromHeader = $params[count($params) - 1]; 

    //return strlen($header); 
    return $fileNameFromHeader; 
}