简体   繁体   English

cURL无法正确保存图像

[英]cURL not saving the image correctly

$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);

... writes the file but invalid (0 bytes). ...写入文件,但无效(0字节)。 Please tell me what I'm doing wrong. 请告诉我我在做什么错。

I ran your code and there were some errors. 我运行了您的代码,出现了一些错误。 I have rectified those here: 我在这里已将其纠正:

$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);

原来的问题是某些图像已加载,但带有302重定向状态消息,这使卷曲感到困惑。

Try add a header() for image type. 尝试为图像类型添加header()。

For example, if it is a PNG image, add in your code: 例如,如果它是PNG图片,请添加代码:

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

Had a play, all you seem to need is the following: 进行了一场表演,您似乎只需要以下内容:

<?
$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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM