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

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


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

The example from the ErrorException page is:

<?phpfunction 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:

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


I just use 'file_exists()':

if (file_exists("must_have.php")) {    require "must_have.php";}else {    echo "Please try back in five minutes...\n";}


A better approach would be to use realpath on the path first. realpath will return false if the file does not exist.

$filename = realpath(getcwd() . "/fileERROR.php5");$filename && return require($filename);trigger_error("Could not find file {$filename}", E_USER_ERROR);

You could even create your own require function in your app's namespace that wraps PHP's require function

namespace app;function require_safe($filename) {  $path = realpath(getcwd() . $filename);  $path && return require($path);  trigger_error("Could not find file {$path}", E_USER_ERROR);}

Now you can use it anywhere in your files

namespace app;require_safe("fileERROR.php5");