[英]How to get file_get_contents() warning instead of the PHP error?
file_get_contents('https://invalid-certificate.com');
Yields the following PHP warning and error: 产生以下PHP警告和错误:
PHP warning: Peer certificate CN='*.invalid-certificate.net' did not match expected CN='invalid-certificate.com'
PHP警告:对等证书CN ='*。invalid-certificate.net'与预期的CN ='invalid-certificate.com'不匹配
PHP error: file_get_contents( https://invalid-certificate.com ): failed to open stream: operation failed
PHP错误: file_get_contents( https://invalid-certificate.com ):无法打开流:操作失败
I want to use exceptions instead of the PHP warning, so: 我想使用异常而不是PHP警告,所以:
$response = @file_get_contents('https://invalid-certificate.com');
if ($response === false) {
$error = error_get_last();
throw new \Exception($error['message']);
}
But now the exception message is: 但是现在异常消息是:
file_get_contents( https://invalid-certificate.com ): failed to open stream: operation failed
file_get_contents( https://invalid-certificate.com ):打开流失败:操作失败
That's normal, error_get_last()
returns the last error … 正常,
error_get_last()
返回最后一个错误 ……
How can I get the warning, which contains much valuable information regarding the failure? 如何获得警告,其中包含有关故障的许多有价值的信息?
You can make good use of set_error_handler and convert those errors into exceptions and use exceptions properly 您可以充分利用set_error_handler并将这些错误转换为异常并正确使用异常
<?php
set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});
try {
$response = file_get_contents('https://invalid-certificate.com');
} catch (ErrorException $e) {
var_dump($e); // ofcourse you can just grab the desired info here
}
?>
A much simpler version would be 一个简单得多的版本是
<?php
set_error_handler(function($errno, $errstr) {
var_dump($errstr);
});
$response = file_get_contents('https://invalid-certificate.com');
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.