【问题标题】:How to check reason why file_get_contents returned false in PHP如何检查 file_get_contents 在 PHP 中返回 false 的原因
【发布时间】:2019-12-21 16:53:57
【问题描述】:

我试过这样做:

$urls = array(


    "https://www.gov.sg/"




);



    foreach ($urls as $url) {
        d($url);
      //  $url = "http://www.google.com";
    $data = file_get_contents($url);
    d($data);

}

d() 是一个类似于 var_dump() 的第 3 方函数。

我不断得到 $data = false。似乎该域中的任何页面都在这样做。

当我尝试另一个域(如 google.com)时,它成功了。

页面有效,我在浏览器上试过了。

以下类似帖子提出了 URL 编码问题,并启用了 allow_url_fopen,但这些在此处并不适用: PHP file_get_contents returning false PHP file_get_contents returning false

为什么函数返回假?另外,一般来说,有没有办法检查为什么 file_get_contents 返回错误? PHP有没有办法转储错误?

【问题讨论】:

    标签: php file debugging error-handling file-get-contents


    【解决方案1】:

    你可以像这样得到最后一个错误,

    $error = error_get_last();
    var_dump($error);
    

    例如,test.php

    <?php
    
    $data = file_get_contents("http://hi200.com");
    var_dump($data);
    $error = error_get_last();
    var_dump($error);
    
    

    php test.php

    PHP Warning:  file_get_contents(http://hi200.com): failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden
     in C:\Users\Dell\Desktop\HQ_Educations\library\test.php on line 3
    bool(false)
    array(4) {
      ["type"]=>
      int(2)
      ["message"]=>
      string(105) "file_get_contents(http://hi200.com): failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden
    "
      ["file"]=>
      string(52) "C:\Users\Dell\Desktop\HQ_Educations\library\test.php"
      ["line"]=>
      int(3)
    }
    

    【讨论】:

      猜你喜欢
      • 2013-01-25
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-25
      • 2016-10-24
      相关资源
      最近更新 更多