PHP Error Handling
In PHP, the default error handling is very simple. An error message is sent to the browser that includes the filename, line number, and a description of the error.
PHP Error Handling
When creating scripts and web applications, error handling is an important part. If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks.
This tutorial introduces some of the most important error-checking methods in PHP.
We will explain different error handling methods:
- Simple "die()" statements
- 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 might get an error like this:
Warning: fopen(welcome.txt) [function.fopen]: failed to open stream:
No such file or directory in /www/tutorialpro/test/test.php on line 2
To avoid the user getting an error message like the one above, we check whether the file exists before attempting to access it:
<?php
if(!file_exists("welcome.txt"))
{
die("File not found");
}
else
{
$file=fopen("welcome.txt","r");
}
?>
Now, if the file does not exist, you get an error message like this:
File not found
The above code is more effective than the previous one because it uses a simple error handling mechanism to terminate the script after an error.
However, simply terminating the script is not always the appropriate method. 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 special 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):
Syntax
error_function(error_level,error_message,
error_file,error_line,error_context)
Parameter | Description |
---|---|
error_level | Required. Specifies the error report level for the user-defined error. Must be a numeric value. See table below: Error Report 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 that contains all variables and their values when the error occurred. |
Error Report Levels
These error report levels are different types of errors that the user-defined error handler can handle:
Value | Constant | Description |
---|---|---|
2 | E_WARNING | Non-fatal run-time errors. Execution of the script is not halted. |
8 | E_NOTICE | Run-time notices. Occurs when the script finds something that might be an error, but could also happen when running a script normally. |
256 | E_USER_ERROR | Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error(). |
512 | E_USER_WARNING | Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error(). |
1024 | E_USER_NOTICE | User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error(). |
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. (In PHP 5.4, E_STRICT became part of E_ALL) |
Now, let's create a function to handle errors:
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Ending Script";
die();
}
The code above is a simple error handling function. When triggered, it captures 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 Up the Error Handler
PHP's default error handler is the built-in error handler. We intend to modify the function above to be the default error handler during script execution.
The error handler can be modified to apply only to certain errors, allowing the script to handle different errors in different ways. However, in this example, we aim 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()
only needs one parameter. A second parameter can be added to specify the error level.
Example
Test the error handler by attempting to output a non-existent variable:
<?php
// Error handling 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 above code is as follows:
Error: [8] Undefined variable: test
Triggering Errors
It is useful to trigger errors at user input points in the script when the input is invalid. In PHP, this task is accomplished with the trigger_error()
function.
Example
In this example, an error occurs if the "test" variable is greater than "1":
<?php
$test=2;
if ($test>1)
{
trigger_error("The variable value must be less than or equal to 1");
}
?>
The output of the above code is as follows:
Notice: The variable value must be less than or equal to 1
in /www/test/tutorialpro.php on line 5
You can trigger errors at any point in your script, and by adding a second parameter, you can specify the type of error.
Possible error types:
E_USER_ERROR - Fatal user-generated run-time error. The error is not recoverable. Script execution is interrupted.
E_USER_WARNING - Non-fatal user-generated run-time warning. Script execution is not interrupted.
E_USER_NOTICE - Default. User-generated run-time notice. Occurs when the script finds a possible error, but could also happen during normal script execution.
Example
In this example, an E_USER_WARNING error occurs 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 handling function
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Script terminated";
die();
}
// Set error handler
set_error_handler("customError",E_USER_WARNING);
// Trigger error
$test=2;
if ($test>1)
{
trigger_error("The variable value must be less than or equal to 1",E_USER_WARNING);
}
?>
The output of the above code is as follows:
Error: [512] The variable value must be less than or equal to 1
Script terminated
Now that we have learned how to create and trigger our own errors, let's look into error logging.
Error Logging
By default, PHP sends error logs to the server's logging system or a file based on the error_log
configuration 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 a good way to get notified of specific errors.
Sending Error Messages via E-Mail
In the following example, we will send an email with the error message and end the script if a specific error occurs:
<?php
// Error handling function
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Notified website administrator";
error_log("Error: [$errno] $errstr",1,
"[email protected]","From: [email protected]");
}
// Set error handler
set_error_handler("customError",E_USER_WARNING);
// Trigger error
$test=2;
if ($test>1)
{
trigger_error("The variable value must be less than or equal to 1",E_USER_WARNING);
}
?>
The output of the above code is as follows:
Error: [512] The variable value must be less than or equal to 1
Notified website administrator
set_error_handler("customError", E_USER_WARNING);
// Trigger an error
$test = 2;
if ($test > 1) {
trigger_error("The variable value must be less than or equal to 1", E_USER_WARNING);
}
?>
The output of the above code is as follows:
Error: [512] The variable value must be less than or equal to 1
Website administrator has been notified
The email received from the above code is as follows:
Error: [512] The 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 the default PHP logging system.