Applications may encounter errors during runtime for various reasons. Some common causes include running out of disk space, invalid user inputs, missing files or database records, insufficient permissions, or temporarily unavailable services.
These errors occur while the script is running, unlike syntax errors which prevent scripts from running at all.
When PHP encounters issues preventing a script from running correctly, it triggers errors represented by integer values and associated constants. The table below outlines several key error levels:
Error Level | Value | Description |
---|---|---|
E_ERROR |
1 |
A critical runtime error that halts script execution immediately. |
E_WARNING |
2 |
A non-fatal runtime warning, allowing script execution to continue. |
E_NOTICE |
8 |
An informational runtime notice indicating a potential issue. |
E_USER_ERROR |
256 |
A fatal error generated by the script using trigger_error() . |
E_USER_WARNING |
512 |
A non-fatal warning generated by the script using trigger_error() . |
E_USER_NOTICE |
1024 |
An informational notice generated by the script using trigger_error() . |
E_STRICT |
2048 |
Advisory message for code compatibility issues. |
E_ALL |
8191 |
All errors and warnings, excluding E_STRICT prior to PHP 5.4.0. |
For more information on error levels, refer to the PHP Error Levels reference.
PHP triggers errors when encountering script issues, but you can also manually trigger errors to provide clearer messages to users. The following section covers common error handling techniques in PHP:
die()
Consider the following example attempting to open a text file for reading:
<?php
// Try to open a non-existent file
$file = fopen("sample.txt", "r");
?>
If the file doesn't exist, an error message similar to this might appear:
By taking a few straightforward precautions, we can avoid users encountering such error messages.
<?php
if(file_exists("sample.txt")){
$file = fopen("sample.txt", "r");
} else{
die("Error: The file you are trying to access doesn't exist.");
}
?>
When running the script above, you'll receive an error message like this:
As demonstrated, by first checking if the file exists before attempting to access it, we can display a more meaningful error message to the user.
The die()
function used in the example simply shows a customized error message and terminates the current script if the 'sample.txt' file is not found.
You have the option to create your own error handler function to manage runtime errors generated by PHP. This custom error handler offers flexibility and control, allowing you to handle errors by displaying a message to the user, logging errors, attempting to fix issues, terminating the script, or ignoring errors altogether.
The custom error handler function must handle at least two parameters (errno and errstr). It can optionally handle three additional parameters (errfile, errline, and errcontext), which provide more details about where and when the error occurred:
Parameter | Description |
---|---|
Required — These parameters are mandatory | |
errno | Indicates the severity of the error as an integer, corresponding to predefined error level constants (E_ERROR , E_WARNING , etc.) |
errstr | Represents the error message as a string |
Optional — These parameters are optional | |
errfile | Specifies the filename of the script where the error occurred, as a string |
errline | Indicates the line number in the script where the error occurred, as a string |
errcontext | An array containing all variables and their values at the time the error occurred, useful for debugging |
Here's a simple example of a custom error handling function, customError()
, which is invoked whenever an error occurs. It displays the error details in the browser and halts script execution:
<?php
// Error handler function
function customError($errno, $errstr){
echo "<b>Error:</b> [$errno] $errstr";
}
?>
To instruct PHP to utilize your custom error handler function, simply invoke the built-in set_error_handler()
function and provide the name of your function as an argument.
<?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);
?>
You can also record error details in a text file, such as:
<?php
function calcDivision($dividend, $divisor){
if($divisor == 0){
trigger_error("calcDivision(): The divisor cannot be zero", E_USER_WARNING);
return false;
} else{
return($dividend / $divisor);
}
}
function customError($errno, $errstr, $errfile, $errline, $errcontext){
$message = date("Y-m-d H:i:s - ");
$message .= "Error: [" . $errno ."], " . "$errstr in $errfile on line $errline, ";
$message .= "Variables:" . print_r($errcontext, true) . "\r\n";
error_log($message, 3, "logs/app_errors.log");
die("There was a problem, please try again.");
}
set_error_handler("customError");
echo calcDivision(10, 0);
echo "This will never be printed.";
?>
You can also send an email containing error details using the error_log()
function.
<?php
function calcDivision($dividend, $divisor){
if ($divisor == 0){
trigger_error("calcDivision(): The divisor cannot be zero", E_USER_WARNING);
return false;
} else{
return($dividend / $divisor);
}
}
function customError($errno, $errstr, $errfile, $errline, $errcontext){
$message = date("Y-m-d H:i:s - ");
$message .= "Error: [" . $errno ."], " . "$errstr in $errfile on line $errline, ";
$message .= "Variables:" . print_r($errcontext, true) . "\r\n";
error_log($message, 1, "webmaster@example.com");
die("There was a problem, please try again. Error report submitted to webmaster.");
}
set_error_handler("customError");
echo calcDivision(10, 0);
echo "This will never be printed.";
?>
While PHP automatically triggers errors for script problems, you can also deliberately trigger errors yourself. This proactive approach can enhance your application's reliability by identifying potential issues before they escalate.
To initiate an error within your script, use the trigger_error()
function and specify the error message you want to generate:
Consider this example function that calculates the division of two numbers:
<?php
function calcDivision($dividend, $divisor){
return($dividend / $divisor);
}
// Calling the function
echo calcDivision(10, 0);
?>
If you pass zero (0) as the $divisor
parameter, PHP will generate an error message like this:
This error message may not provide sufficient information. Here's an example that demonstrates using the trigger_error()
function to create a more meaningful error.
<?php
function calcDivision($dividend, $divisor){
if($divisor == 0){
trigger_error("The divisor cannot be zero", E_USER_WARNING);
return false;
} else{
return($dividend / $divisor);
}
}
// Calling the function
echo calcDivision(10, 0);
?>
Now, if the script encounters this situation, it will display the following error message:
As you can see, the error message from the second example provides a clearer explanation of the issue compared to the previous one.