我正在尝试阅读一个文件的一部分。但是文件托管服务器在标题处返回强制下载。
我可以使用fopen,fread来读取文件的一部分。
$f = fopen('http://www.hdwallpapers.org/download/beautiful-red-tree-scene-1280x800.jpg','r');
$response = fread($f, 3); echo $response.'<br>';
echo $response;exit();
但是当我切换到使用CURL
时$curl = curl_init('http://www.hdwallpapers.org/download/beautiful-red-tree-scene-1280x800.jpg');
curl_setopt($curl, CURLOPT_TIMEOUT, 5);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl, CURLOPT_HTTPHEADER, $headers );
curl_setopt($curl, CURLOPT_RANGE, "0-2");
$response = curl_exec($curl);echo $response.'<br>';
它没有任何回报。
这是文件头:
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:Keep-Alive
Content-Disposition:attachment; filename=beautiful-red-tree-scene-1280x800.jpg
Content-Length:427882
Content-Transfer-Encoding:binary
Content-Type:application/force-download
Date:Sat, 26 Oct 2013 04:11:25 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive:timeout=5, max=75
Pragma:no-cache
Server:Apache
那么,如何使用CURL读取部分强制下载文件?
答案 0 :(得分:0)
您可以使用以下代码
进行尝试function grab_image($url,$saveto){
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$raw=curl_exec($ch);
curl_close ($ch);
if(file_exists($saveto)){
unlink($saveto);
}
$fp = fopen($saveto,'x');
fwrite($fp, $raw);
fclose($fp);
}
答案 1 :(得分:0)
你只想阅读文件?还是强行下载?无论如何..这里是如何阅读它。
$link = 'http://www.hdwallpapers.org/download/beautiful-red-tree-scene-1280x800.jpg';
$curl = curl_init($link);
curl_setopt($curl, CURLOPT_TIMEOUT, 5);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt ($curl, CURLOPT_HTTPHEADER, $headers );
curl_setopt($curl, CURLOPT_RANGE, "0-2");
$response = curl_exec($curl);
$data = base64_encode ($response);
echo "<img src='data:image/jpeg;base64,{$data}'>";