我如何使用curl在头文件中获取文件名? [英] How can I get file name from header using curl in php?
本文介绍了我如何使用curl在头文件中获取文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我用php获取时,如何确定标题中的文件名。锁在这里:
how can i determine the file name in header when i get with php. lock at this:
<?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);
推荐答案
创建一个读取头文件并自行解析的回调函数。例如:
Create a callback that reads headers, and parse them yourself. Something like:
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
这篇关于我如何使用curl在头文件中获取文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文