全球主机交流论坛

标题: 一张奇怪的图片 [打印本页]

作者: 机长    时间: 2024-5-17 16:55
标题: 一张奇怪的图片
用php怎么都无法获取完整的图片,但是浏览器是可以正常打开的。

  1. <?php
  2. function displayImage($url) {
  3.     // 重试次数
  4.     $maxRetries = 3;
  5.     $retryCount = 0;

  6.     do {
  7.         // 初始化cURL
  8.         $ch = curl_init($url);
  9.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  10.         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  11.         curl_setopt($ch, CURLOPT_TIMEOUT, 300); // 设置超时时间
  12.         curl_setopt($ch, CURLOPT_FAILONERROR, true);

  13.         // 获取图片内容
  14.         $imageContent = curl_exec($ch);

  15.         // 获取HTTP状态码
  16.         $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  17.         $curlError = curl_error($ch);
  18.         curl_close($ch);

  19.         if ($httpCode === 200) {
  20.             break; // 成功下载,退出循环
  21.         }

  22.         $retryCount++;
  23.     } while ($retryCount < $maxRetries);

  24.     if ($httpCode !== 200) {
  25.         echo "无法获取图片内容。HTTP状态码: " . $httpCode . " 错误: " . $curlError;
  26.         return;
  27.     }

  28.     // 获取图片的MIME类型
  29.     $imageInfo = getimagesizefromstring($imageContent);
  30.     if ($imageInfo === FALSE) {
  31.         echo "无法识别图片格式。";
  32.         return;
  33.     }
  34.    
  35.     $mimeType = $imageInfo['mime'];

  36.     // 设置适当的Content-Type头
  37.     header("Content-Type: $mimeType");

  38.     // 显示图片
  39.     echo $imageContent;
  40. }

  41. // 调用函数显示图片
  42. displayImage("http://thumb.zgjiemeng.com/d/file/contents/2019/10/5da985cd42edd.jpg");
  43. ?>
复制代码

作者: 箫璃蔫    时间: 2024-5-17 17:43
图都没有,你在说什么,而且你不会试试国内的图片?
作者: 机长    时间: 2024-5-17 17:47
箫璃蔫 发表于 2024-5-17 17:43
图都没有,你在说什么,而且你不会试试国内的图片?

1、代码中包含了图片url,看不懂php就闭嘴。
2、图片服务器在HK,如果你认为不是国内的那算哪的?
作者: icon    时间: 2024-5-17 17:51
本帖最后由 icon 于 2024-5-17 17:53 编辑

有啥额外检测吧,比如ua

  1. root@iZuf610otwtqjmygenx33wZ:/tmp# wget http://thumb.zgjiemeng.com/d/file/contents/2019/10/5da985cd42edd.jpg
  2. --2024-05-17 17:51:05--  http://thumb.zgjiemeng.com/d/file/contents/2019/10/5da985cd42edd.jpg
  3. Resolving thumb.zgjiemeng.com (thumb.zgjiemeng.com)... 8.217.155.9
  4. Connecting to thumb.zgjiemeng.com (thumb.zgjiemeng.com)|8.217.155.9|:80... connected.
  5. HTTP request sent, awaiting response... 403 Forbidden
  6. 2024-05-17 17:51:05 ERROR 403: Forbidden.
复制代码


作者: 祭徐坤    时间: 2024-5-17 18:01
查request header呗这有啥好奇怪的
作者: qingzhuzi    时间: 2024-5-17 18:03
查request header呗这有啥好奇怪的
作者: inla    时间: 2024-5-17 18:16
换这里面的图片可以
https://hostloc.gdisk.cf/forum.php?mod=viewthread&tid=1305908
作者: 胖虎_    时间: 2024-5-17 18:28
浏览器可以正常打开是什么意思,是访问这个图片地址可以正常显示吗?
用代码去获取的时候,需要带上请求头,等等一些信息。有些图片会有防盗设置的。
作者: 瞄人缝    时间: 2024-5-17 18:33
指定字符集
curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
// 获取图片内容 上面添加

话说 又在爬站了吗
作者: 机长    时间: 2024-5-17 18:40
瞄人缝 发表于 2024-5-17 18:33
指定字符集
curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
// 获取图片内容 上面添加

可以了,牛逼啊! 高铁上爬了个站





欢迎光临 全球主机交流论坛 (https://hostloc.gdisk.cf/) Powered by Discuz! X3.4