【问题标题】:Will file_get_contents fail gracefully?file_get_contents 会优雅地失败吗?
【发布时间】:2011-05-07 02:33:24
【问题描述】:

我需要file_get_contents 具有容错能力,例如,如果提供给它的$url 返回一个404,请在它发出警告之前告诉我它。这个可以吗?

【问题讨论】:

    标签: php file-get-contents


    【解决方案1】:

    任何使用 HTTP 包装器访问远程文件的函数,就好像它是本地的一样,将在本地范围内自动生成一个名为 $http_response_header 的本地变量。您可以访问该变量以查找有关在远程文件上调用 fopenfile_get_contents ... 时发生的情况的信息。

    您可以使用@: @file_get_contents 取消警告。

    如果您不关心错误是什么,您可以使用@file_get_contents 并将结果与​​false 进行比较:

    $content = @file_get_contents(url);
    if ($content === false) { /* failure */ } else { /* success */ }
    

    【讨论】:

      【解决方案2】:

      例如,您可以执行额外的 (HEAD) 请求来首先找出答案

      $response = get_headers($url);
      if($response[1] === 'HTTP/1.1 200 OK') {
          $content = file_get_contents($url);
      }
      

      或者您可以告诉file_get_contents 忽略任何错误并通过修改流上下文来强制获取$url 的结果:

      echo file_get_contents(
          'http://www.example.com/foo.html',
          FALSE,
          stream_context_create(array('http'=>array('ignore_errors' => TRUE)))
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-09-25
        • 2017-01-03
        • 1970-01-01
        • 1970-01-01
        • 2018-11-01
        • 1970-01-01
        • 2019-06-18
        相关资源
        最近更新 更多