首页 > 解决方案 > curl 或 wget 获取无效的 jpg 图像,但浏览器获取有效图像

问题描述

我像这样运行命令

wget https://odis.homeaway.com/odis/listing/5895882c-6c65-47f5-b782-e13b8246e4aa.c10.jpg

我尝试使用 curl 获取上面的图像,返回的图像是无效的 jpg 图像。当我尝试使用浏览器并将图像另存为时,我得到有效的 jpg 图像。即使我尝试使用 file_get_contents 它也会返回 false。

    $image = 'https://odis.homeaway.com/odis/listing/5895882c-6c65-47f5-b782-e13b8246e4aa.c10.jpg'
    $image_data = file_get_contents($image);
    try {
        echo 'saving';
        $image1 = imagecreatefromjpeg($image_data);

    } catch (Exception $ex) {
        echo 'error';
    }

如何使用 、 或 获得curlwget图像file_get_contents

标签: phpimagecurlwget

解决方案


这是odis.homeaway.com服务器的错误,您应该向他们的网站管理员发送错误报告。

他们的服务器总是在https://odis.homeaway.com/odis/listing/5895882c-6c65-47f5-b782-e13b8246e4aa.c10.jpg gzip 压缩中发送图像,即使客户端没有指定accept-encoding: gzip。wget 根本不支持 gzip 压缩,但 curl 支持。在他们修复服务器之前,您可以通过--compressed在命令行版本中设置参数或CURLOPT_ENCODING=>'gzip'在 curl_api 中设置或通过 gzdecode() 运行它来告诉 curl 自动为您解压缩它,例如$image_data = gzdecode(file_get_contents($image));(gzdecode() 方法不是推荐,因为一旦他们真正修复了他们的服务器,这将停止工作,并且现在只能工作,因为他们的服务器被窃听了)。您的浏览器不受该错误影响的原因是所有主流浏览器始终Accept-Encoding: gzip默认发送(和其他浏览器)。

编辑:原来我提到gzuncompress(),不是gzdecode(),那是一个错误,正确的解压功能是gzdecode()


推荐阅读