How to catch error of require() or include() in PHP?

R_User picture R_User · Nov 24, 2011 · Viewed 26.2k times · Source

I'm writing a script in PHP5 that requires the code of certain files. When A file is not available for inclusion, first a warning and then a fatal error are thrown. I'd like to print an own error message, when it was not possible to include the code. Is it possible to execute one last command, if requeire did not work? the following did not work:

require('fileERROR.php5') or die("Unable to load configuration file.");

Supressing all error messages using error_reporting(0) only gives a white screen, not using error_reporting gives the PHP-Errors, which I don't want to show.

Answer

Sjan Evardsson picture Sjan Evardsson · Dec 31, 2012

You can accomplish this by using set_error_handler in conjunction with ErrorException.

The example from the ErrorException page is:

<?php
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
set_error_handler("exception_error_handler");

/* Trigger exception */
strpos();
?>

Once you have errors being handled as exceptions you can do something like:

<?php
try {
    include 'fileERROR.php5';
} catch (ErrorException $ex) {
    echo "Unable to load configuration file.";
    // you can exit or die here if you prefer - also you can log your error,
    // or any other steps you wish to take
}
?>