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 ( https://www.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!
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.