如何在PHP中处理file_get_contents()函数的警告?

Was*_*eem 290 php warnings exception-handling function

我写了这样的PHP代码

$site="http://www.google.com";
$content = file_get_content($site);
echo $content;
Run Code Online (Sandbox Code Playgroud)

但当我删除"http://"时,$site我收到以下警告:

警告:file_get_contents(www.google.com)[function.file-get-contents]:无法打开流:

我尝试过try,catch但它没有用.

Roe*_*oel 477

第1步:检查返回码: if($content === FALSE) { // handle error here... }

步骤2:通过在调用file_get_contents()之前放置一个错误控制操作符(即@)来抑制警告: $content = @file_get_contents($site);

  • 请记住使用严格比较:if($ content === FALSE).如果文件包含"0",则会触发误报. (80认同)
  • 不要这样做。您只需抑制错误警告即可。这不是错误处理!这会给调试带来问题。 (5认同)
  • 嗨,这对我不起作用,添加@仍然导致E_WARNING被一些全局(不是我的)错误处理程序捕获,并且我的脚本在我有机会处理返回值之前就死了.有任何想法吗?TNX. (4认同)
  • 虽然答案很老,但我仍然建议在答案中添加一个注释,使用"@"可能会对性能产生负面影响.请参阅相关帖子中的[此答案](http://stackoverflow.com/a/2002789/1369473). (4认同)
  • 检测到副作用:如果文件不存在,脚本将在 @file_get_contents 行处停止。 (2认同)

eno*_*rev 134

您还可以将错误处理程序设置匿名函数,该函数调用Exception并对该异常使用try/catch.

set_error_handler(
    function ($severity, $message, $file, $line) {
        throw new ErrorException($message, $severity, $severity, $file, $line);
    }
);

try {
    file_get_contents('www.google.com');
}
catch (Exception $e) {
    echo $e->getMessage();
}

restore_error_handler();
Run Code Online (Sandbox Code Playgroud)

似乎有很多代码可以捕获一个小错误,但如果你在整个应用程序中使用异常,你只需要在顶部(例如,在一个包含的配置文件中)执行此操作,它将会将所有错误转换为异常.

  • @lolka_bolka 因为 file_get_contents 不会抛出异常,而是抛出 php 错误。所以这个例子所做的是设置一个“错误处理程序”来捕获大多数抛出的 php 错误实例,并将这些错误转换为异常。这是文档中的一个更现代的示例:http://php.net/manual/en/class.errorexception.php#errorexception.examples (2认同)
  • @enobrev 不要忘记在抛出异常之前恢复匿名函数内的错误处理程序。异常可以被处理,在这种情况下,处理程序仍然设置为抛出这个特定的异常,这可能会出乎意料,并在异常处理中出现另一个错误时引入奇怪的、难以调试的行为。 (2认同)
  • 我建议在 finally 块中包含 restore_error_handler() 调用 (2认同)

Lau*_*rie 66

我最喜欢这样做的方法很简单:

if (!$data = file_get_contents("http://www.google.com")) {
      $error = error_get_last();
      echo "HTTP request failed. Error was: " . $error['message'];
} else {
      echo "Everything went better than expected";
}
Run Code Online (Sandbox Code Playgroud)

我在使用try/catch上面的@enobrev 进行实验后发现了这一点,但这样可以减少冗长(和IMO,更易读)的代码.我们只是error_get_last用来获取最后一个错误的文本,并file_get_contents在失败时返回false,因此一个简单的"if"可以捕获它.

  • 这将触发未返回正文的成功请求的错误,或返回计算结果为false的错误.应该是`if(false!==($ data = file_get_contents()))` (9认同)
  • 第一个条件是倒退。如果 false 不等于 file_get_contents 调用的结果,那么它得到了一些内容,我们不应该寻找错误。我很困惑看到以前的测试中的错误,或者当真正找到谷歌时看到 $error 为空的错误! (3认同)
  • 这是解决这个问题的最简单,最好的解决方案!也许让它`@file_get_contents`来向浏览器提供错误报告. (2认同)

Gre*_*reg 33

您可以添加@: $content = @file_get_contents($site);

这会压制任何警告 - 谨慎使用!.请参见错误控制操作符

编辑:当您删除'http://'时,您不再需要网页,而是磁盘上名为"www.google ....."的文件


Ara*_*yan 20

另一种方法是抑制错误,并抛出一个稍后可以捕获的异常.如果在代码中多次调用file_get_contents(),这尤其有用,因为您不需要手动抑制和处理所有这些调用.相反,可以在单个try/catch块中对此函数进行多次调用.

// Returns the contents of a file
function file_contents($path) {
    $str = @file_get_contents($path);
    if ($str === FALSE) {
        throw new Exception("Cannot access '$path' to read contents.");
    } else {
        return $str;
    }
}

// Example
try {
    file_contents("a");
    file_contents("b");
    file_contents("c");
} catch (Exception $e) {
    // Deal with it.
    echo "Error: " , $e->getMessage();
}
Run Code Online (Sandbox Code Playgroud)


小智 14

这是我如何做到的......不需要试试块...最好的解决方案始终是最简单的...享受!

$content = @file_get_contents("http://www.google.com");
if (strpos($http_response_header[0], "200")) { 
   echo "SUCCESS";
} else { 
   echo "FAILED";
} 
Run Code Online (Sandbox Code Playgroud)

  • -1:如果您收到404错误或其他内容,则此方法有效,但如果您根本无法连接到服务器(例如,错误的域名),则无效.我认为`$ http_response_header`在这种情况下不会更新,因为没有收到HTTP响应. (4认同)

Raf*_*shi 14

function custom_file_get_contents($url) {
    return file_get_contents(
        $url,
        false,
        stream_context_create(
            array(
                'http' => array(
                    'ignore_errors' => true
                )
            )
        )
    );
}

$content=FALSE;

if($content=custom_file_get_contents($url)) {
    //play with the result
} else {
    //handle the error
}
Run Code Online (Sandbox Code Playgroud)


小智 6

这是我如何处理:

$this->response_body = @file_get_contents($this->url, false, $context);
if ($this->response_body === false) {
    $error = error_get_last();
    $error = explode(': ', $error['message']);
    $error = trim($error[2]) . PHP_EOL;
    fprintf(STDERR, 'Error: '. $error);
    die();
}
Run Code Online (Sandbox Code Playgroud)


小智 5

最好的办法是设置自己的错误和异常处理程序,这将执行一些有用的操作,例如将其记录在文件中或通过电子邮件发送关键文件。 http://www.php.net/set_error_handler