Question

I am using require_once in my php scripts, and I would like to know the correct way of writing the code so it handles errors if this fails.

At the moment, I just use require_once('included_file.php'); I'm thinking use this:

if (!@require_once('included_file.php')){
//log error, print nice error message, and exit;
}

Is this "good practice", or is there a different/better way to do it. I have read through this page ( http://us3.php.net/manual/en/language.operators.errorcontrol.php ) and see the use of OR DIE, but I am just not sure the best way to go.

Thanks!

Was it helpful?

Solution

If a require* call fails, the script is halted immediately, no other code will execute. You cannot handle a require_once error gracefully. You can configure your web server to handle it with an error page, should the PHP process die unsuccessfully. Otherwise you'll have to use basically the code you're showing, but using include_once. You should not use @ to suppress the resulting error, but just turn off error display instead so the error will be logged.

Having said all that, you should use require* for files which are required for your script to run. You should not even write any additional code to handle the situation where those files aren't available, because that means your application is in an entirely unusable state. If all required files aren't even present, the application should not even be deployed to a production server and hence should not need any graceful error handling. Some errors you really want to punch you in the face; missing critical files is one of them.

OTHER TIPS

require_once will trigger a compilation error. Therefore, execution will halt and the custom logging will not take pace

see the documentation for require http://www.php.net/manual/en/function.require.php

require is identical to include except upon failure it will also produce a fatal
E_COMPILE_ERROR level error. In other words, it will halt the script whereas
include only emits a warning (E_WARNING) which allows the script to continue.

Including file using required_once means that the script will stop executing if it cannot able to load the given file. It is good to use require_once on certain criteria. Its depend upon the importance of the inclusion file.

Well - initial thought is that PHP is already handling 2/3 of what you want - logging the fatal error and exiting if a required file fails to load. It sounds like the real problem is just that you want a "pretty" errors page of some sorts - this page has a pretty good walkthrough of how to set that up - http://papermashup.com/create-an-error-page-to-handle-all-errors-with-php/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top