PHP Error Handling
In PHP, default error handling is simple. An error message is sent to the browser, containing the filename, line number, and a message describing the error.
PHP Error Handling
Error handling is an important part when creating scripts and web applications. If your code lacks error detection coding, the program looks unprofessional and opens 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 for you:
- 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 will get an error like this:
Warning: fopen(welcome.txt) [function.fopen]: failed to open stream: No such file or directory in /www/example/test/test.php on line 2
To avoid users getting an error message like the one above, we check whether the file exists before accessing it:
<?php
if(!file_exists("welcome.txt"))
{
die("文件不存在");
}
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 above code is more effective, 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 approach. Let's examine alternative PHP functions used to handle errors.
Creating a Custom Error Handler
Creating a custom error handler is very simple. We simply create 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 it 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 where the error occurred. |
| error_context | Optional. Specifies an array containing each variable and their values in use when the error occurred. |
Error Reporting Levels
These error reporting levels are the different types of errors handled by the user-defined error handler:
| Value | Constant | Description |
|---|---|---|
| 2 | E_WARNING | Non-fatal run-time errors. Do not halt script execution. |
| 8 | E_NOTICE | Run-time notices. Occur when the script detects a possible error, but may also occur when the script is running normally. |
| 256 | E_USER_ERROR | Fatal user-generated errors. These are similar to E_ERROR set by the programmer using the PHP function trigger_error(). |
| 512 | E_USER_WARNING | Non-fatal user-generated warnings. These are similar to E_WARNING set by the programmer using the PHP function trigger_error(). |
| 1024 | E_USER_NOTICE | User-generated notices. These are similar to E_NOTICE set by the programmer using the PHP function trigger_error(). |
| 4096 | E_RECOVERABLE_ERROR | Catchable fatal errors. 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 that handles errors:
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "脚本结束";
die();
}
The code above is a simple error handling function. When it is triggered, it takes the error level and error message. Then it 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 this function.
Setting the Error Handler
PHP's default error handler is the built-in error handler. We intend to turn the above function into the default error handler during script execution.
The error handler can be modified so that it only applies to certain errors, allowing the script to handle different errors in different ways. However, in this example, we intend 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 this error handler by attempting to output a variable that does not exist:
<?php
// 错误处理函数
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr";
}
// 设置错误处理函数
set_error_handler("customError");
// 触发错误
echo($test);
?>
The output of the above code is shown below:
Error: [8] Undefined variable: test
Triggering Errors
In places in the script where user data is input, it is useful to trigger errors when the user's input is invalid. In PHP, this task is done by 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("变量值必须小于等于 1");
}
?>
The output of the above code is shown below:
Notice: 变量值必须小于等于 1 in /www/test/example.php on line 5
You can trigger errors anywhere in your script. By adding the second parameter, you can specify the type of error triggered.
Possible error types:
- E_USER_ERROR - Fatal user-generated run-time error. The error cannot be recovered from. 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 detects a possible error, but may also occur when the script is running normally.
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
// 错误处理函数
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "脚本结束";
die();
}
// 设置错误处理函数
set_error_handler("customError",E_USER_WARNING);
// 触发错误
$test=2;
if ($test>1)
{
trigger_error("变量值必须小于等于 1",E_USER_WARNING);
}
?>
The output of the above code is shown below:
Error: [512] 变量值必须小于等于 1 脚本结束
Now that we have learned how to create our own errors and how to trigger them, let's next look at error logging.
Error Logging
By default, depending on the error_log configuration in php.ini, PHP sends error logs to the server's logging system or a file. By 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 about specific errors.
Sending Error Messages via E-Mail
In the following example, if a specific error occurs, we will send an email with the error message and end the script:
<?php
// 错误处理函数
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "已通知网站管理员";
error_log("Error: [$errno] $errstr",1,
"[email protected]","From: [email protected]");
}
// 设置错误处理函数
set_error_handler("customError",E_USER_WARNING);
// 触发错误
$test=2;
if ($test>1)
{
trigger_error("变量值必须小于等于 1",E_USER_WARNING);
}
?>
The output of the above code is shown below:
Error: [512] 变量值必须小于等于 1 已通知网站管理员
The email received from the above code is shown below:
Error: [512] 变量值必须小于等于 1
This method is not suitable for all errors. Regular errors should be logged on the server using the default PHP logging system.
Other Extensions