PHP error handl...LOGIN

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

When creating scripts and web applications Error treatment is an important part. 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 treatment methods for you:

· Simple "DIE ()" statement

## · Customized definition Error and error trigger

· Error report


# This Basic error treatment: Use DIE () function

## The first example shows a simple script that opens the text file: r



## If the file does not exist, you will get the following errors like this:

##11: FOPEN (error.txt) [function.fopen]: failed to Open Stream:
No Such File or Directory in /www/php/test/test.php on LINE 2

This is to avoid users from getting similar errors, we are visiting File previously detected if the file exists:

<?php
$open=fopen('error.txt','r');
echo $open;
?>

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 efficient 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

Create a custom The 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):

error_function

(error_level,error_message,error_file,error_line,error_context)#####################Required. Specifies error messages for user-defined errors.
Parameter Description
## error_level


Required. Specifies the error reporting level for user-defined errors. Must be a number. See the table below: Error reporting levels.


error_message

## error_file

Optional. Specifies the file name where the error occurred.

error_line error_context

Error reporting levels

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

Optional. Specifies the line number where the error occurred.
Optional. Specifies an array containing each variable in use when the error occurred and their values.
## 2E_WARNINGNon-fatal run-time error. Do not pause script execution. ##      
Value Constant Description

  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().

User-generated notification. This is similar to E_NOTICE set by the programmer using the PHP function trigger_error(). ##     

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

<?php
header("Content-type:text/html;charset=utf-8");
if(!file_exists('error.txt')){
    die("文件不存在");
}else{
    $file=fopen('error.txt','r');
}
?>

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 handler

PHP’s default error handler is 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 to handle all errors, set_error_handler() requires only one parameter, and a second parameter can be added to specify the error level


Example

We combine the knowledge we learned above and try to output non-existent variables to test this error handler:

<?php
header("Content-type:text/html;charset=utf-8");
function customError($errno, $errstr)
{
    echo "<b>Error:</b> [$errno] $errstr<br>";
    echo "脚本结束";
    die();
}
?>

The program running result:

Error: [8] Undefined variable: test

The running result tells us The error level is 8 and the error message is: Non-existent variable


triggers error

The location where the user enters data in the script , 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:

<?php
header("Content-type:text/html;charset=utf-8");
// 错误处理函数
function customError($errno, $errstr)
{
    echo "<b>Error:</b> [$errno] $errstr";
}
// 设置错误处理函数
set_error_handler("customError");
// 触发错误
echo($test);
//关闭了所有的错误显示
error_reporting(0);
//显示所有错误
//error_reporting(E_ALL);
//显示所有错误,但不显示提示
//error_reporting(E_ALL & ~ E_NOTICE);
?>

Program running result:

Notice: The variable value must be less than or equal to 1 in D:\WWW\Advanced tutorial\error\error_1.php on line 6


You can trigger errors anywhere in the script. By adding the second parameter, you can specify the error level that is triggered.

Possible error types:

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

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

· 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", the E_USER_WARNING error occurs. If E_USER_WARNING occurs, we will use our custom error handler and end the script:

<?php
header("Content-type:text/html;charset=utf-8");
$test=2;
if ($test>1)
{
    trigger_error("变量值必须小于等于 1");
}
?>

Program execution result:

Error: [512] Variable value must be Less than or equal to 1
End of script

The running result tells us that the value of the error level is 512. The error message becomes the prompt message we set with the trigger_error function


Error logging

In some companies, there is a special log collection system. The log collection system will silently help you collect errors, warnings, and prompts behind the scenes.

There are also some companies that do not have a dedicated log collection system and collect the running logs from the server through files.

Among them: PHP errors and warnings must be received.

Then the question comes - if users are not allowed to see it, and the error reporting level is set, how to collect errors into the log system?

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

## 1024


E_USER_NOTICE

  4096



E_RECOVERABLE_ERROR

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

Error message type Description
0Send to the default error_log specified location
1 Send to the specified email location
3Send to the specified file location

Example

<?php
header("Content-type:text/html;charset=utf-8");
// 错误处理函数
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);
}
?>

Example

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

<?php
//无法连接到数据库服务器,直接记录到php.ini 中的error_log指定位置
error_log("无法连接到数据库服务器服务器");
//可以发送邮件,但是php.ini必须配置过邮件系统
error_log('可以用邮件报告错误,让运维人员半夜起床干活',1 ,'liwenkai@phpxy.com');
//记录在指定的位置
error_log("我是一个错误哟", 3, "d:/test/my-errors.log");
?>

Program running results :

Error: [512] Value must be 1 or belowWebmaster has been notified

The email received from the above code looks like this:

Error: [512] Value must be 1 or below

This method is not suitable for all errors. General errors should be logged on the server using the default PHP logging system.

Note: Sending emails in error_log may be unfamiliar to beginners, so you don’t need to master some knowledge.


error_reporting Report error type

error_reporting refers to the error Report. There is also such a parameter in php.ini. this parameter. Determines which error types the PHP engine records, reports, and displays.

1. Set the error_reporting parameter in php.ini. If the error_reporting parameter is set to 0. Errors in the entire PHP engine will not be displayed, output, or recorded. It will not be recorded in the logging that will be discussed in the next chapter.

If we want to show all errors we can write:

error_reporting = E_ALL

Want to show all errors but exclude Tip, you can write this parameter as:

##error_reporting = E_ALL & ~ E_NOTICE

Displays all errors, but excludes prompts, compatibility and Future compatibility. Can be written as:

##error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED

#2. In some cases, what should we do if we do not have permission to operate the php.ini file and want to control error_reporting?


At the beginning of the running xxxx.php file, we can use the error_reporting() function to achieve the goal.

<?php
 //error handler function
 function customError($errno, $errstr)
 {
     echo "<b>Error:</b> [$errno] $errstr<br />";
     echo "Webmaster has been 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("Value must be 1 or below",E_USER_WARNING);
 }
 ?>

You can try the above code and try to write the wrong code intentionally. Whether the specified error will be displayed in the current file.

[Expand and understand knowledge points]:

@ symbol is a single line that we have learned before that does not display errors , please do not use or use less @ symbol.

Example

Let's read a non -existent file.Next Section

<?php header("Content-type:text/html;charset=utf-8"); // 错误处理函数 function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr"; } // 设置错误处理函数 set_error_handler("customError"); // 触发错误 echo($test); //关闭了所有的错误显示 error_reporting(0); //显示所有错误 //error_reporting(E_ALL); //显示所有错误,但不显示提示 //error_reporting(E_ALL & ~ E_NOTICE); ?>
submitReset Code
ChapterCourseware
    None