PHP error handling

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.

PHP Error Handling

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:

1. Simple "die()" statement

2. Custom errors and error triggers

3. Error reporting

Basic error handling: using the die() function

The first example shows an open Simple script for a text file:

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/php/test/test.php on line 2

In order to avoid users getting error messages similar to the above , we detect whether the file exists before accessing it:

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 the appropriate approach. Let's examine alternative PHP functions for handling errors.

Create a custom error handler

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):

Syntax

error_function(error_level, error_message, error_file, error_line, error_context)

##Parameterserror_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.

Error reporting levels

These error reporting levels are different types of errors handled by user-defined error handlers:

valueconstantDescription

## 2 E_Warning non-fatal raun-time error. Do not pause script execution.

8 E_NOTICE run-time notification. 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 notification. This is similar to E_NOTICE set by the programmer using the PHP function trigger_error().

4096 E_RECOVERABLE_ERROR Trapable fatal error. Like 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 becomes part of E_ALL)

In the above types:

1. The error is the most serious and must be resolved. Otherwise, the program cannot continue to execute

2. warning is also very important. Tong also must be solved. If it is clear and intentional, you don’t need to deal with it

3. Notice You don’t need to deal with it. But in some companies, project standards are particularly high. It must also be solved in projects with high standard requirements. Because notice will affect the execution efficiency of PHP. Usually occurs when the function is not defined, etc.

4. Parse error refers to a syntax error or typo, which must be solved

5. all represents all errors of all types

Now, let's create a function that handles errors:

function customError($errno, $errstr)
"Script ends";
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 trigger the function.

Set the error handlerPHP’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.

You can modify the error handler so that it only applies to certain errors, so that the script can handle different errors in different ways. 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 can handle all errors, set_error_handler() requires only one parameter, and a second parameter can be added to specify the error level.

Example

Test this error handler by trying to output a variable that does not exist:

Error: [$errno] $errstr"; } // 设置错误处理函数 set_error_handler("customError"); // 触发错误 echo($test); ?>

The output of the above code will look like this:

Error: [8] Undefined variable: test


Trigger errorat The location in the script where the user enters data, useful for triggering an error when the user's input is invalid. In PHP, this task is accomplished by the trigger_error() function.

Example

In this example, if the "test" variable is greater than "1", an error will occur:

1) { trigger_error("变量值必须小于等于 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/php.php on line 5


You can Anywhere an error is triggered, by adding a second parameter you can specify the error level that is triggered.

Possible error types:

1. E_USER_ERROR - Fatal user-generated run-time error. The error cannot be recovered. Script execution was interrupted.

2. E_USER_WARNING - Non-fatal user-generated run-time warning. Script execution is not interrupted.

3. 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.

Example

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:

Error: [$errno] $errstr
"; 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 will look like this:

Error: [512] Variable value Must be less than or equal to 1

End of script

Now that we have learned how to create our own errors and how to trigger them, let's study error records.

Error record

Here are the relevant configuration items that need to be used in php.ini. These two configuration items are:

Parameters offDescription:The log_errors and log_errors_max_len in the table are very easy to understand.And error_log specifies the path on which errors will be stored. The syslog in the configuration items may be a bit difficult to understand. syslog refers to system recording. Windows system is in the log collector of the computer. Linux defaults to: /etc/syslog.conf

By default, according to the error_log configuration in php.ini, PHP sends error records to the server's recording system or file. By using the error_log() function, you can send error records to a specified file or remote destination.

Emailing yourself an error message is a good way to get notified of a specified error.

Send error message via E-Mail

In the following example, if a specific error occurs, we will send an error message with email, and end the script:

Error: [$errno] $errstr
"; echo "已通知网站管理员"; error_log("Error: [$errno] $errstr",1, "someone@example.com","From: webmaster@example.com"); } // 设置错误处理函数 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 as follows:

Error: [512] The variable value must be less than or equal to 1

Already Notify the website administrator

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. General errors should be logged on the server using the default PHP logging system.

Continuing Learning
||
Error: [$errno] $errstr
"; echo "脚本结束"; die(); } // 设置错误处理函数 set_error_handler("customError",E_USER_WARNING); // 触发错误 $test=2; if ($test>1) { trigger_error("变量值必须小于等于 1",E_USER_WARNING); } ?>
submit Reset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!