cURL无法正确保存图像

时间:2012-11-19 09:18:08

标签: php curl

$ch = curl_init();
$fp = fopen("$localName",'w');

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_URL, $src);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
curl_setopt($ch, CURLOPT_TIMEOUT, 200);
curl_setopt($ch, CURLOPT_AUTOREFERER, false);
curl_setopt($ch, CURLOPT_REFERER, "http://google.com");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$rawdata=curl_exec ($ch);
curl_close ($ch);

fwrite($fp, $rawdata); 
fclose($fp);

...写入文件但无效(0字节)。请告诉我我做错了什么。

4 个答案:

答案 0 :(得分:1)

我运行了你的代码并且有一些错误。我在这里纠正了这些:

$src = '<URL to the image>';
$ch = curl_init($src);

//curl_setopt($ch, CURLOPT_FILE, $fp); This option is not required
//curl_setopt($ch, CURLOPT_URL, $host); Since you are setting the source in init skip this
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
curl_setopt($ch, CURLOPT_TIMEOUT, 200);
curl_setopt($ch, CURLOPT_AUTOREFERER, false);
curl_setopt($ch, CURLOPT_REFERER, "http://google.com");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); // Follows redirect responses.

$raw=curl_exec($ch);
if ($raw === false) {
    trigger_error(curl_error($ch));
}

curl_close ($ch);
$localName = basename($src); // The file name of the source can be used locally       
if(file_exists($localName)){    
    unlink($localName);
}

$fp = fopen($localName,'wb');
fwrite($fp, $raw);
fclose($fp);

答案 1 :(得分:1)

原来问题是一些图像被加载但是302重定向状态消息使卷曲混乱。

答案 2 :(得分:0)

尝试为图像类型添加标题()。

例如,如果是PNG图像,请添加代码:

// ...
header('Content-type: image/png');
file_put_contents($raw);

答案 3 :(得分:0)

有一个游戏,你似乎需要的是以下内容:

<?
$src = 'http://bit.ly/TT5N5M';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $src);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$output = curl_exec($ch);
curl_close($ch);

$fp = fopen("img.jpg",'w');
fwrite($fp, $output);
fclose($fp);