【问题标题】:Could not download image using php (bad request)无法使用 php 下载图像(错误请求)
【发布时间】:2016-10-30 14:50:42
【问题描述】:

我正在尝试从 url 下载图像,尝试了多种方法(几乎我在 google 上找到的所有方法)但尚未成功, 一些解决方案给出错误

Found Document has been moved here

大多数解决方案都会出错

file_get_content: failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request

到目前为止我尝试过的解决方案之一(我尝试过超过 25 个)

$fp = fopen ('mydirectory/image.jpg', 'w+');              // open file handle

$ch = curl_init('https://www.otakusmash.com/read-manga/mangas/AIKI/008/Aiki_v02_c08_000.jpg');
            // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // enable if you want
curl_setopt($ch, CURLOPT_FILE, $fp);          // output to file
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1000);      // some large value to allow curl to run for a long time
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
curl_setopt($ch, CURLOPT_VERBOSE, true);   // Enable this line to see debug prints
curl_exec($ch);
curl_close($ch);                              // closing curl handle
fclose($fp);

请帮帮我

【问题讨论】:

  • 如果您修复文件路径的引号,则代码有效。为什么你认为它不起作用?
  • 修复了这个问题,但它只从这个特定的域下载 0 kb 的图像。

标签: php curl web-scraping


【解决方案1】:

您的代码有错误,请使用以下代码

$fp = fopen ("mydirectory/image.jpg", 'w+');              // open file handle

$ch = curl_init('https://www.otakusmash.com/read-manga/mangas/AIKI/008/Aiki_v02_c08_000.jpg');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // enable if you want
curl_setopt($ch, CURLOPT_FILE, $fp);          // output to file
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1000);      // some large value to allow curl to run for a long time
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
curl_setopt($ch, CURLOPT_VERBOSE, true);   // Enable this line to see debug prints
curl_exec($ch);
curl_close($ch);                              // closing curl handle
fclose($fp);

【讨论】:

  • 谢谢,太棒了。像魅力一样工作,你能告诉我出了什么问题吗? :)
  • 这一行是评论 -- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  • @NomanAli 当您尝试从https 下载任何东西时,请使用上面的行。
猜你喜欢
  • 1970-01-01
  • 2020-05-13
  • 2016-10-11
  • 2012-10-19
  • 1970-01-01
  • 1970-01-01
  • 2020-08-15
  • 1970-01-01
  • 2022-01-22
相关资源
最近更新 更多