In PHP, the default error handling is simple. An error message is sent to the browser with the file name, line number, and a message describing the error.
Error handling is an important part when creating scripts and Web applications. If your code lacks error detection coding, the program will look unprofessional and open the door to security risks.
This tutorial introduces some of the most important error detection methods in PHP.
We will explain different error handling methods to you:
Simple "die()" statement
Custom errors and error triggers
error report
The first example shows a simple script that opens a text file:
<?php$file=fopen("welcome.txt","r");?>
If the file does not exist, you will get an error like this:
Warning: fopen(welcome.txt) [function.fopen]: failed to open stream:No such file or directory in /www/codercto/test/test.php on line 2
To avoid users getting error messages like the one above, we check whether the file exists before accessing it:
<?phpif(!file_exists("welcome.txt")){ die("File does not exist");}else{ $file=fopen("welcome.txt","r");}?>
Now, if the file does not exist, you will get an error message like this:
File does not exist
The above code is more efficient than the previous code because it uses a simple error handling mechanism to terminate the script after an error.
However, simply terminating the script is not always appropriate. Let's examine alternative PHP functions for handling errors.
Creating a custom error handler is very simple. We simply created a dedicated function that can be called when an error occurs in PHP.
The function must be able to handle at least two parameters (error level and error message), but can accept up to five parameters (optional: file, line-number and error context):
error_function(error_level,error_message,error_file,error_line,error_context)
parameter | describe |
---|---|
error_level | Required. Specifies the error reporting level for user-defined errors. Must be a number. See the table below: Error reporting levels. |
error_message | Required. Specifies error messages for user-defined errors. |
error_file | Optional. Specifies the file name where the error occurred. |
error_line | Optional. Specifies the line number where the error occurred. |
error_context | Optional. Specifies an array containing each variable in use when the error occurred and their values. |
These error reporting levels are different types of errors handled by user-defined error handlers:
value | constant | describe |
---|---|---|
2 | E_WARNING | Nonfatal run-time error. Do not pause script execution. |
8 | E_NOTICE | run-time notifications. Occurs when the script finds a possible error, but can also occur when the script is running normally. |
256 | E_USER_ERROR | Fatal user-generated error. This is similar to E_ERROR set by the programmer using the PHP function trigger_error(). |
512 | E_USER_WARNING | Non-fatal user-generated warning. This is similar to the E_WARNING set by the programmer using the PHP function trigger_error(). |
1024 | E_USER_NOTICE | User-generated notifications. This is similar to E_NOTICE set by the programmer using the PHP function trigger_error(). |
4096 | E_RECOVERABLE_ERROR | Trapable fatal errors. Like E_ERROR, but can be caught by user-defined handlers. (See set_error_handler()) |
8191 | E_ALL | All errors and warnings. (In PHP 5.4, E_STRICT becomes part of E_ALL) |
Now, let's create a function that handles errors:
function customError($errno, $errstr){ echo "<b>Error:</b> [$errno] $errstr<br>"; echo "End of script"; die();}
The above code is a simple error handling function. When it is triggered, it gets the error level and error message. It then prints the error level and message, and terminates the script.
Now that we have created an error handling function, we need to determine when to fire it.
PHP's default error handler is the built-in error handler. We are going to transform the above function into the default error handler when the script is running.
Error handlers can be modified to apply only to certain errors, so that the script can handle different errors differently. However, in this case we are going to use our custom error handler for all errors:
set_error_handler("customError");
Since we want our custom function to handle all errors, set_error_handler() requires only one argument, and a second argument can be added to specify the error level.
Test this error handler by trying to print a variable that doesn't exist:
<?php// Error handling function function customError($errno, $errstr){ echo "<b>Error:</b> [$errno] $errstr";}// Set error handling function set_error_handler("customError") ;//Trigger error echo($test);?>
The output of the above code looks like this:
Error: [8] Undefined variable: test
Where the user enters data in a script, it is useful to trigger an error when the user's input is invalid. In PHP, this task is accomplished by the trigger_error() function.
In this example, if the "test" variable is greater than "1", an error occurs:
<?php$test=2;if ($test>1){ trigger_error("Variable value must be less than or equal to 1");}?>
The output of the above code looks like this:
Notice: Variable value must be less than or equal to 1in /www/test/codercto.php on line 5
You can trigger an error anywhere in the script, and by adding a second parameter, you can specify the error level that is triggered.
Possible error types:
E_USER_ERROR - Fatal user-generated run-time error. The error cannot be recovered. Script execution was interrupted.
E_USER_WARNING - Non-fatal user-generated run-time warning. Script execution is not interrupted.
E_USER_NOTICE - Default. User-generated run-time notifications. Occurs when the script finds a possible error, but can also occur when the script is running normally.
In this example, if the "test" variable is greater than "1", an E_USER_WARNING error occurs. If E_USER_WARNING occurs, we will use our custom error handler and end the script:
<?php// Error handling function customError($errno, $errstr){ echo "<b>Error:</b> [$errno] $errstr<br>"; echo "End of script"; die(); }//Set the error handling function set_error_handler("customError",E_USER_WARNING);//Trigger error $test=2;if ($test>1){ trigger_error("Variable value must be less than or equal to 1",E_USER_WARNING);}?>
The output of the above code looks like this:
Error: [512] Variable value must be less than or equal to 1. End of script
Now that we've learned how to create our own errors and how to trigger them, let's look at error logging.
By default, PHP sends error logs to the server's logging system or file, depending on the error_log configuration in php.ini. By using the error_log() function, you can send error records to a specified file or remote destination.
E-mailing yourself an error message is a good way to get notified of a specified error.
In the example below, if a specific error occurs, we will send an email with an error message and end the script:
<?php// Error handling function customError($errno, $errstr){ echo "<b>Error:</b> [$errno] $errstr<br>"; echo "The website administrator has been notified"; error_log ("Error: [$errno] $errstr",1, "[email protected]","From: [email protected]");}// Set the error handling function set_error_handler("customError",E_USER_WARNING); // Trigger error $test=2;if ($test>1){ trigger_error("Variable value must be less than or equal to 1",E_USER_WARNING);}?>
The output of the above code looks like this:
Error: [512] The variable value must be less than or equal to 1. The website administrator has been notified
The email received from the above code looks like this:
Error: [512] Variable value must be less than or equal to 1
This method is not suitable for all errors. General errors should be logged on the server using the default PHP logging system.