This section contains the detail aboutError handling in PHP
Error handling in PHP
Your application must have an error handling codes. Without it, it looks very unprofessional.
PHP have following error handling methods :
- die() method
- setting custom error handler and error triggering
- error reporting
die() method
You can use die() method as follows :
<?php if(!file_exists("welcome.txt")) { die("File not found"); } else { $file=fopen("welcome.txt","r"); } ?>
It will show the following message :
File not found
setting custom error handler and error triggering
For creating custom error handler, you need to follow the syntax as given below :
error_function(error_level,error_message,error_file,error_line,error_context)
The custom error handler must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, line-number, and the error context).
In given below example, we create a custom error handler plus also set it for error handling using set_error_handler() function as follows :
<?php //error handler function function MyErrorHandler($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr"; } //set error handler set_error_handler("MyErrorHandler"); //trigger error echo($test); ?>
The output of the following code is given below :
Error: [8] Undefined variable: test
Error triggering
You can trigger an error as follows :
<?php //error handler function function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr<br />"; echo "Ending Script"; die(); } //set error handler set_error_handler("customError",E_USER_WARNING); //trigger error $test=2; if ($test>1) { trigger_error("Value must be 1 or below",E_USER_WARNING); } ?>
In the above example, an E_USER_WARNING occurs if the "test" variable is bigger than "1". If an E_USER_WARNING occurs we will use our custom error handler and end the script:
The output is given below :
Error: [512] Value must be 1 or below
Ending Script
error reporting
PHP sends an error log to the servers logging system or a file, depending on how the error_log configuration is set in the php.ini file. By using the error_log() function you can send error logs to a specified file or a remote destination as follows :
<?php //error handler function function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr<br />"; echo "Webmaster has been notified"; error_log("Error: [$errno] $errstr",1, "person@example.com","From: admin@example.com"); } //set error handler set_error_handler("customError",E_USER_WARNING); //trigger error $test=2; if ($test>1) { trigger_error("Value must be 1 or below",E_USER_WARNING); } ?>
The output is given below as follows :
Error: [512] Value must be 1 or below
Webmaster has been notified
And the content of the received mail will be :
Error: [512] Value must be 1 or below
[ 0 ] Comments