【问题标题】:Unable to catch PHP file_get_contents error using try catch block无法使用 try catch 块捕获 PHP file_get_contents 错误
【发布时间】:2019-03-21 12:05:41
【问题描述】:

我正在尝试使用file_get_contents 函数获取图像,但它给出了错误。为了处理错误,我使用了 try catch 块,但它没有捕获错误并失败。

我的代码:

try {
     $url = 'http://wxdex.ocm/pdd.jpg'; //dummy url
     $file_content = file_get_contents($url);
}
catch(Exception $e) {
     echo 'Error Caught';           
}

错误:

Warning: file_get_contents(): php_network_getaddresses: getaddrinfo failed: No such host is known
Warning: file_get_contents(http://wxdex.ocm/pdd.jpg): failed to open stream: php_network_getaddresses: getaddrinfo failed: No such host is known.

注意:: 我可以在远程获取任何其他有效的图片网址。

【问题讨论】:

标签: php error-handling


【解决方案1】:

try/catch 不起作用,因为 warning 不是 exception

您可以尝试这段代码,这样您也可以捕获警告。

//set your own error handler before the call
set_error_handler(function ($err_severity, $err_msg, $err_file, $err_line, array $err_context)
{
    throw new ErrorException( $err_msg, 0, $err_severity, $err_file, $err_line );
}, E_WARNING);

try {
    $url = 'http://wxdex.ocm/pdd.jpg';
    $file_content = file_get_contents($url);
} catch (Exception $e) {
    echo 'Error Caught'; 
}

//restore the previous error handler
restore_error_handler();

【讨论】:

  • 在自动将警告转换为异常时要小心:如果您没有在正确的位置明确捕获它,任何小问题都会中止整个程序。此外,set_error_handler() 会覆盖您之前定义的任何处理程序。
  • @ÁlvaroGonzález 这就是我在那之后使用 restore_error_handler() 的原因
  • 超级修复.. 它帮了我很多
【解决方案2】:

以下是另一种方式,只需要检查数据,如果没有我们可以抛出异常来处理它。与设置新的错误处理程序相比会更安全

try {
    $url = 'http://wxdex.ocm/pdd.jpg';
    $file_content = file_get_contents($url);
    if(empty($file_content)){
       throw new Exception("failed to open stream ", 1);
    }else{
       echo "File is loaded and content is there";
     }

} catch (Exception $e) {
   echo 'Error Caught'; 
}

【讨论】:

  • 不幸的是,这不起作用。它会发出警告,所以我不得不使用 @ 来抑制警告。不过还是谢谢。
【解决方案3】:

使用get header函数检查URL是否存在

$url = 'http://wxdex.ocm/pdd.jpg';
$file_headers = @get_headers($url);

if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found' ||trim($file_headers[0]) == 'HTTP/1.1 403 Forbidden') {
    $exists = false;
}else{
    $exists = true;
}
if($exists===true){

    $file_content = file_get_contents($url);
}

【讨论】:

  • 这不是很好的解决方案,因为@get_headers() 只是消除错误或警告。我们可以直接使用@file_get_contents() 来查看它是否返回任何值。
猜你喜欢
  • 2013-07-18
  • 1970-01-01
  • 2015-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-08
  • 2019-01-12
相关资源
最近更新 更多