1

我正在尝试读取一个文件的一部分。但是文件托管服务器在标题处作为强制下载返回。

我可以使用 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 读取强制下载文件的一部分呢?

4

2 回答 2

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);
}
于 2013-10-26T04:32:58.413 回答
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}'>";
于 2013-10-26T04:48:17.907 回答