How to get file_get_contents () warning instead of PHP error?

file_get_contents('https://invalid-certificate.com');

Sets the following PHP warnings and errors:

PHP Warning: Certificate peer CN = '*. invalid-certificate.net 'does not match expected CN =' invalid-certificate.com '

PHP error: file_get_contents ( https://invalid-certificate.com ): could not open the stream: operation failed


I want to use exceptions instead of warning PHP, therefore:

$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:

file_get_contents ( https://invalid-certificate.com ): could not open the stream: operation failed

This normal one error_get_last()returns the last error ...

, ?

+4
1

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
}
?>

<?php
set_error_handler(function($errno, $errstr) {
    var_dump($errstr);
});
$response = file_get_contents('https://invalid-certificate.com');
?>

Fiddle

+1

All Articles