Matthieu Napoli
Matthieu Napoli

Reputation: 49693

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 warning: Peer certificate CN='*.invalid-certificate.net' did not match expected CN='invalid-certificate.com'

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


I want to use exceptions instead of the PHP warning, so:

$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

That's normal, error_get_last() returns the last error

How can I get the warning, which contains much valuable information regarding the failure?

Upvotes: 4

Views: 1845

Answers (1)

Hanky Panky
Hanky Panky

Reputation: 46900

You can make good use of set_error_handler and convert those errors into exceptions and use exceptions properly

<?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');
?>

Fiddle

Upvotes: 1

Related Questions