Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 229
R_User Avatar asked Nov 24 '11 19:11

R_User


People also ask

What are the difference between include () and require () file in PHP?

Use require when the file is required by the application. Use include when the file is not required and application should continue when file is not found.

How can I catch exception in PHP?

Because exceptions are objects, they all extend a built-in Exception class (see Throwing Exceptions in PHP), which means that catching every PHP exception thrown is as simple as type-hinting the global exception object, which is indicated by adding a backslash in front: try { // ... } catch ( \Exception $e ) { // ... }

What are include () and require () functions in PHP?

The include() function does not stop the execution of the script even if any error occurs. The require() function will stop the execution of the script when an error occurs. The include() function does not give a fatal error.

Which function gives fatal error if file is not included?

In the case of the require_once(), if the file PHP file is missing, then a fatal error will arise and no output is shown and the execution halts.


2 Answers

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 } ?> 
like image 70
Sjan Evardsson Avatar answered Sep 19 '22 14:09

Sjan Evardsson


I just use 'file_exists()':

if (file_exists("must_have.php")) {     require "must_have.php"; } else {     echo "Please try back in five minutes...\n"; } 
like image 21
Nicholas Rezmerski Avatar answered Sep 21 '22 14:09

Nicholas Rezmerski