无法使用PHP CURL下载远程图像

时间:2020-02-17 01:35:38

标签: php curl php-curl

编辑:我通过scrapestack与支持人员联系,并确认其api不支持图像文件。

我正在尝试使用CURL和php下载远程图像。下面是我的代码。但是每当我尝试打开下载的图像时,总会得到:

Cannot read this file. This is not a valid bitmap file, or its format is not currently supported.

有人知道我的代码有什么问题吗?谢谢。

$image ="http://api.scrapestack.com/scrape?access_key=TOKEN-HERE&url=https://i.imgur.com/Cbiu8Ef.png";
$imageName = pathinfo( $image, PATHINFO_BASENAME );
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $image );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTP_CONTENT_DECODING, false);
$source = curl_exec( $ch );
$info = curl_getinfo($ch);
curl_close( $ch );
file_put_contents( $imageName, $source );

我无法打开文件,当我试图以崇高的态度打开文件时,它卡在了加载图像中。当我用记事本打开它时,得到的内容看起来像是PNG图像,但它不是有效的图像。文件开头 PNG

IHDR       �   q�I�    IDATx�k�]�u�o��(��_�M��m�8:���_r�G

您可以在此处查看文件:https://gofile.io/?c=cfsYf2

问题似乎是通过Scrapestack发出卷曲请求,因为如果我直接将卷曲指向图像url,则图像将正确下载,如下所示:

$image ="https://i.imgur.com/Cbiu8Ef.png";

3 个答案:

答案 0 :(得分:1)

编辑:我今天还玩了scrapestack,它似乎不支持图像抓取。最好是可以与他们的客户支持联系并找到答案。

@Towsif是正确的,您正在尝试获取页面,而不是实际图像。我很快就整理好了东西,尝试看看是否适合您。

$queryString = http_build_query([
  'access_key' => 'replace this with your own token',
  'url' => 'https://i.imgur.com/Cbiu8Ef.png',
]);

$ch = curl_init(sprintf('%s?%s', 'http://api.scrapestack.com/scrape', $queryString));
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
$image_source = curl_exec( $ch );
curl_close( $ch );
file_put_contents( 'Cbiu8Ef.png' , $image_source );

答案 1 :(得分:0)

您的问题出在这个网址上。

$image ="http://api.scrapestack.com/scrape?access_key=TOKEN-HERE&url=https://imgur.com/a/E5ehGuv";

如果您转到此网址

https://imgur.com/a/E5ehGuv

您将看到图像页面,但 NOT 图像路径。 pathinfo()函数在这里不起作用,并引发错误。

如果右键单击该图像并在新标签页中打开图像,您将看到图像路径,在这种情况下为

https://i.imgur.com/Cbiu8Ef.png

因此您可以尝试使用此网址

$image ="http://api.scrapestack.com/scrape?access_key=TOKEN-HERE&url=https://i.imgur.com/Cbiu8Ef.png";

答案 2 :(得分:0)

您似乎收到的响应是损坏的 PNG图片。

如果您使用PHP的版本为 5.1.3之前的版本,则需要为二进制数据传输指定其他选项,例如图像:

curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);

如果上述选项不能解决问题,您可以尝试设置

curl_setopt($ch, CURLOPT_HTTP_CONTENT_DECODING, false);

如果响应中的Content-Type标头设置有误,则会导致curl对原始输出进行不必要的解码。