PHP error handling experience sharing_PHP tutorial
This tutorial covers some of the most important error detection methods in PHP.
We will explain different error handling methods to you:
Simple "die()" statement
Custom errors and error triggers
Error reporting
Basic Error handling: using the die() function
The first example shows a simple script to open a text file:
$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 C:webfoldertest.php on line 2 In order to avoid users getting error messages like the above, we check whether the file exists before accessing it:
if(!file_exists("welcome.txt"))
{
die("File not found");
}
else
{
$file=fopen("welcome.txt","r");
}
?>
现在,假如文件不存在,您会得到类似这样的错误消息:
File not found比起之前的代码,上面的代码更有效,这是由于它采用了一个简单的错误处理机制在错误之后终止了脚本。
不过,简单地终止脚本并不总是恰当的方式。让我们研究一下用于处理错误的备选的 PHP 函数。
创建自定义错误处理器
创建一个自定义的错误处理器非常简单。我们很简单地创建了一个专用函数,可以在 PHP 中发生错误时调用该函数。
该函数必须有能力处理至少两个参数 (error level 和 error message),但是可以接受最多五个参数(可选的:file, line-number 以及 error context):
语法
error_function(error_level,error_message,
error_file,error_line,error_context)
参数 | 描述 |
---|---|
error_level |
必需。为用户定义的错误规定错误报告级别。必须是一个值数。 参见下面的表格:错误报告级别。 |
error_message | 必需。为用户定义的错误规定错误消息。 |
error_file | 可选。规定错误在其中发生的文件名。 |
error_line | 可选。规定错误发生的行号。 |
error_context | 可选。规定一个数组,包含了当错误发生时在用的每个变量以及它们的值。 |
错误报告级别
这些错误报告级别是错误处理程序旨在处理的错误的不同的类型:
值 | 常量 | 描述 |
---|---|---|
2 | E_WARNING | 非致命的 run-time 错误。不暂停脚本执行。 |
8 | E_NOTICE |
Run-time 通知。 脚本发现可能有错误发生,但也可能在脚本正常运行时发生。 |
256 | E_USER_ERROR | 致命的用户生成的错误。这类似于程序员使用 PHP 函数 trigger_error() 设置的 E_ERROR。 |
512 | E_USER_WARNING | 非致命的用户生成的警告。这类似于程序员使用 PHP 函数 trigger_error() 设置的 E_WARNING。 |
1024 | E_USER_NOTICE | 用户生成的通知。这类似于程序员使用 PHP 函数 trigger_error() 设置的 E_NOTICE。 |
4096 | E_RECOVERABLE_ERROR | 可捕获的致命错误。类似 E_ERROR,但可被用户定义的处理程序捕获。(参见 set_error_handler()) |
8191 | E_ALL |
所有错误和警告,除级别 E_STRICT 以外。 (在 PHP 6.0,E_STRICT 是 E_ALL 的一部分) |
function customError($errno, $ errstr)
{
echo "Error: [$errno] $errstr
";
echo "Ending Script";
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 fire it.
Set Error Handler
PHP’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.
The error handler can be modified 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 argument, a second argument can be added to specify the error level.
Example
Test this error handler by trying to output a variable that does not exist:
//error handler function
function customError($errno, $errstr)
{
echo "Error:}
//set error handler
set_error_handler("customError");
//trigger error
echo($ test);
?>
The output of the above code should be similar to this:
Error: [8] Undefined variable: test triggers the error
User in the script The location of the input data, useful for triggering an error when the user's input is invalid. In PHP, this task is accomplished by trigger_error().
Example
In this example, if the "test" variable is greater than "1", an error will occur:
$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below ");
}
?>
The output of the above code should be similar to this:
Notice: Value must be 1 or below
in C: webfoldertest.php on line 6 You can trigger errors anywhere in the script. By adding a 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. The script found a possible error, which may have occurred while the script was running normally.
Example
In this example, if the "test" variable is greater than "1", the E_USER_WARNING error occurs. If an E_USER_WARNING occurs, we will use our custom error handler and end the script:
//error handler function
function customError($errno, $errstr)
{
echo "Error: [$errno] $ errstr
";
echo "Ending Script";
die();
}
//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);
}
?>
The output of the above code should look like this:
Error: [512] Value must be 1 or below
Ending Script now , we have learned how to create our own errors and how to punish them, now let's study error records.
Error logging
By default, PHP sends error logging to the server's error logging system or file according to the error_log configuration in php.ini. 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 great way to get notified of a specified error.
Send error message via Email
In the example below, if a specific error occurs, we will send an email with an error message and end the script:
//error handler function
function customError($errno, $errstr)
{
echo "Error: [$errno] $errstr
";
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);
}
?>
The output of the above code should be similar to this:
Error: [512] Value must be 1 or below
Webmaster has been notifiedThe email received from the above code should be similar to 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.
Error backtrace
Definition and usage
The PHP debug_backtrace() function generates a backtrace.
This function returns an associative array. The following elements may be returned:
Name | Type | Description |
---|---|---|
function | String | Current function name. |
line | Integer | Current line number. |
file | String | The current file name. |
class | 字符串 | 当前的类名 |
object | 对象 | 当前对象。 |
type | 字符串 | 当前的调用类型,可能的调用:
|
args | 数组 | 如果在函数中,列出函数参数。如果在被引用的文件中,列出被引用的文件名。 |
debug_backtrace()例子
function one($str1, $str2)
{
two("Glenn", "Quagmire");
}
function two($str1, $str2)
{
three("Cleveland", "Brown");
}
function three($str1, $str2)
{
print_r(debug_backtrace());
}
one("Peter", "Griffin");
?>
输出:
Array
(
[0] => Array
(
[file] => C:webfoldertest.php
[line] => 7
[function] => three
[args] => Array
(
[0] => Cleveland
[1] => Brown
)
)
[1] => Array
(
[file] => C:webfoldertest.php
[line] => 3
[function] => two
[args] => Array
(
[0] => Glenn
[1] => Quagmire
)
)
[2] => Array
(
[file] => C:webfoldertest.php
[line] => 14
[function] => one
[args] => Array
(
[0] => Peter
[1] => Griffin
)
)
)

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
