PHP Error Handling
In PHP, the default error handling is very simple. An error message is sent to the browser, containing the filename, line number, and a description of the error.
PHP Error Handling
Error handling is an important part of creating scripts and web applications. If your code lacks error detection, your application will appear unprofessional and open security vulnerabilities.
This tutorial introduces some of the most important error detection methods in PHP.
We will cover different error handling approaches:
- A simple
die()statement - Custom errors and error triggers
- Error reporting
Basic Error Handling: Using the die() Function
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//test/test.php on line 2
To prevent users from seeing errors like the one above, we check whether the file exists before attempting to access it:
<?php if(!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
Compared to the previous code, the code above is more effective because it uses a simple error handling mechanism that terminates the script after an error occurs.
However, simply terminating the script is not always appropriate. Let's explore alternative PHP functions for handling errors.
Creating a Custom Error Handler
Creating a custom error handler is very simple. We simply create a specialized function that will be called whenever 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):
Syntax
error_function(error_level,error_message, error_file,error_line,error_context)
| Parameter | Description |
|---|---|
| error_level | Required. Specifies the error-reporting level for the user-defined error. Must be a number. See the table below: Error Reporting Levels. |
| error_message | Required. Specifies the error message for the user-defined error. |
| error_file | Optional. Specifies the filename in which the error occurred. |
| error_line | Optional. Specifies the line number in which the error occurred. |
| error_context | Optional. Specifies an array containing every variable and their values in the scope where the error occurred. |
Error Reporting Levels
These error reporting levels represent the different types of errors handled by user-defined error handlers:
| Value | Constant | Description |
|---|---|---|
| 2 | E_WARNING | Non-fatal run-time errors. Execution of the script is not paused. |
| 8 | E_NOTICE | Run-time notices. Issued when the script finds something that might be an error, but could also occur during normal script execution. |
| 256 | E_USER_ERROR | Fatal user-generated error. This is similar to an E_ERROR set by the programmer using PHP's trigger_error() function. |
| 512 | E_USER_WARNING | Non-fatal user-generated warning. This is similar to an E_WARNING set by the programmer using PHP's trigger_error() function. |
| 1024 | E_USER_NOTICE | User-generated notice. This is similar to an E_NOTICE set by the programmer using PHP's trigger_error() function. |
| 4096 | E_RECOVERABLE_ERROR | Catchable fatal error. Similar to E_ERROR, but can be caught by a user-defined handler (see set_error_handler()). |
| 8191 | E_ALL | All errors and warnings (E_STRICT became part of E_ALL in PHP 5.4). |
Now, let's create a function to handle errors:
function customError($errno, $errstr){echo "<b>Error:</b> [$errno] $errstr<br>";echo "Script ended";die();}
The code above is a simple error handling function. When triggered, it receives the error level and error message. It then outputs the error level and message, and terminates the script.
Now that we have created an error handling function, we need to determine when to trigger it.
Setting an Error Handler
PHP's default error handler is built-in. We want to make our custom function the default error handler for the duration of the script.
You can modify the error handler so that it only applies to certain errors, allowing the script to handle different errors in different ways. However, in this example, we want 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 parameter. A second parameter can be added to specify the error level.
Example
Test this error handler by trying to output an undefined variable:
<?php // Error handler function
function customError($errno, $errstr){
echo "<b>Error:</b> [$errno] $errstr";
}
// Set error handler
set_error_handler("customError");
// Trigger error
echo($test);
?>
The output of the code above will be:
Error: Undefined variable: test
Triggering Errors
It is useful to trigger errors where user input data is expected in a script, especially when user input is invalid. In PHP, this task is performed by the trigger_error() function.
Example
In this example, an error will occur if the "test" variable is greater than "1":
<?php $test=2;if ($test>1){trigger_error("Variable value must be less than or equal to 1");}?>
The output of the code above will be:
Notice: Variable value must be less than or equal to 1 in /www/test/.php on line 5
You can trigger an error anywhere in a script. By adding a second parameter, you can specify the type of error to be triggered.
Possible error types:
E_USER_ERROR- Fatal user-generated run-time error. Cannot be recovered from. Script execution is halted.E_USER_WARNING- Non-fatal user-generated run-time warning. Script execution is not halted.E_USER_NOTICE- Default. User-generated run-time notice. Issued when the script finds something that might be an error, but could also occur during normal script execution.
Example
In this example, an E_USER_WARNING error will occur if the "test" variable is greater than "1". If an E_USER_WARNING occurs, we will use our custom error handler and end the script:
<?php // Error handler function
function customError($errno, $errstr){
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Script ended";
die();
}
// Set error handler
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 code above will be:
Error: Variable value must be less than or equal to 1Script ended
Now that we have learned how to create our own errors and how to trigger them, let's examine error logging.
Error Logging
By default, PHP sends error logs to the server's system logger or a file, as specified by the error_log directive in php.ini. Using the error_log() function, you can send error logs to a specified file or remote destination.
Sending error messages to yourself via email is an excellent way to receive notifications about specific errors.
Sending Error Messages via Email
In the following example, if a specific error occurs, we will send an email containing the error message and then terminate the script:
<?php // Error handler function
function customError($errno, $errstr){
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Administrator notified";
error_log("Error: [$errno] $errstr",1,"someone@example.com","From: webmaster@example.com");
}
// Set error handler
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 code above will be:
Error: Variable value must be less than or equal to 1Administrator notified
The email received from the code above will look like this:
Error: Variable value must be less than or equal to 1
This method is not suitable for all errors. Regular errors should be logged on the server using PHP's default logging system.
YouTip