【问题标题】:PHP fopen keeps failing for input URLPHP fopen 不断输入 URL 失败
【发布时间】:2021-04-05 05:54:55
【问题描述】:

我正在使用 PHP 并尝试运行此代码示例:

<?php
  // $target = "http://www.example.com/";
  $target = "http://www.schrenk.com/nostarch/webbots/hello_world.html";
  $output = "";

  // Fetch the file.
  if($file_handle = fopen($target, 'r')) {
    while (($buffer = fgets($file_handle, 4096)) !== false) {
      $output = $output . $buffer;
    }
    if(!feof($file_handle)) {
      $output = "Error: Unexpected fgets fail\n";
    }
    fclose($file_handle);
  } else {
    die("Error: fopen failed\n");
  }
  echo $output;
?>

我不断收到上述 URL 的此错误:

Warning: fopen(http://www.schrenk.com/nostarch/webbots/hello_world.html/): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in <code.php> on line 3

但是,该代码适用于其他 URL,例如“http://www.example.com”、“https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview”等。

请帮我调试一下。

【问题讨论】:

  • http://www.schrenk.com/nostarch/webbots/hello_world.html 怎么样(去掉末尾的斜杠/)?
  • 如果您在浏览器中打开:http://www.schrenk.com/nostarch/webbots/hello_world.html/ 它将显示 404 未找到,而 http://www.schrenk.com/nostarch/webbots/hello_world.html 将正常打开。所以从 URL 中删除最后一个 /
  • 另外,rawurlencode($target) 的意义何在?顺便说一句,如果这仍然不适用于fopen(),它可能会被机器人禁止。
  • 让我更新代码。同样不添加斜杠也会给我同样的问题。我是使用 rawurlencode,首先调试代码。我已将其从代码示例中删除。
  • @ServingQuarantineperiod 您好。请至少尝试运行 PHP 代码,而不仅仅是访问网站。

标签: php fopen


【解决方案1】:

正如怀疑的那样,该站​​点不允许机器人从中读取数据。作为一种解决方法,您可以模拟浏览器用户代理,使站点相信请求来自实际浏览器。此外,使用fopen() 阅读也很乏味。如果您只想完整捕获响应,curl 是一个更好的选择。

片段:

<?php

try{
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, 'http://www.schrenk.com/nostarch/webbots/hello_world.html');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER , true);
  curl_setopt($ch, CURLOPT_USERAGENT , "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36");
  $response = curl_exec($ch);

  if(curl_errno($ch) !== 0){
     throw new \Exception(curl_error($ch));
  }

  curl_close($ch);
  echo $response;
}catch(\Exception $e){
  die("Error: " . $e->getMessage());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    相关资源
    最近更新 更多