Home > Backend Development > PHP Tutorial > Usage and examples of PHP error handling functions

Usage and examples of PHP error handling functions

墨辰丷
Release: 2023-03-29 17:10:01
Original
1746 people have browsed it

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

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:

Simple "die()" statement

Custom errors and error triggers

Error reporting

Basic error handling: use the die() function

First This example shows a simple script that opens a text file:

<?php
$file=fopen("welcome.txt","r");
?>
Copy after login

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 errors similar to the above message, we check if the file exists before accessing it:

<?php
if(!file_exists("welcome.txt"))
{
die("File not found");
}
else
{
$file=fopen("welcome.txt","r");
}
?>
Copy after login

Now, if the file does not exist, you will get an error message like this:

File not found

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)


ParametersDescription
error_levelRequired. Specifies the error reporting level for user-defined errors. Must be a number. See the table below: Error reporting levels.
error_messageRequired. Specifies error messages for user-defined errors.
error_fileOptional. Specifies the file name where the error occurred.
error_lineOptional. Specifies the line number where the error occurred.
error_contextOptional. Specifies an array containing each variable in use when the error occurred and their values.

错误报告级别

这些错误报告级别是用户自定义的错误处理程序处理的不同类型的错误:

现在,让我们创建一个处理错误的函数:

function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Ending Script";
die();
}
Copy after login

上面的代码是一个简单的错误处理函数。当它被触发时,它会取得错误级别和错误消息。然后它会输出错误级别和消息,并终止脚本。

现在,我们已经创建了一个错误处理函数,我们需要确定在何时触发该函数。


ValueConstantDescription
2 E_WARNING Non-fatal run-time error. Do not pause script execution.
8E_NOTICErun-time notification. Occurs when the script finds a possible error, but can also occur when the script is running normally.
256E_USER_ERRORFatal user-generated error. This is similar to E_ERROR set by the programmer using the PHP function trigger_error().
512E_USER_WARNINGNon-fatal user-generated warning. This is similar to the E_WARNING set by the programmer using the PHP function trigger_error().
1024E_USER_NOTICE User-generated notification. This is similar to E_NOTICE set by the programmer using the PHP function trigger_error().
4096E_RECOVERABLE_ERRORCatchable fatal error. Like E_ERROR, but can be caught by a user-defined handler. (See set_error_handler())
8191E_ALLAll errors and warnings. (In PHP 5.4, E_STRICT becomes part of E_ALL)


设置错误处理程序

PHP 的默认错误处理程序是内建的错误处理程序。我们打算把上面的函数改造为脚本运行期间的默认错误处理程序。

可以修改错误处理程序,使其仅应用到某些错误,这样脚本就能以不同的方式来处理不同的错误。然而,在本例中,我们打算针对所有错误来使用我们自定义的错误处理程序:

set_error_handler("customError");
Copy after login

由于我们希望我们的自定义函数能处理所有错误,set_error_handler() 仅需要一个参数,可以添加第二个参数来规定错误级别。

实例

通过尝试输出不存在的变量,来测试这个错误处理程序:

Error: [$errno] $errstr";
}
//set error handler
set_error_handler("customError");
//trigger error
echo($test);
?>
Copy after login

以上代码的输出如下所示:

Error: [8] Undefined variable: test

触发错误

在脚本中用户输入数据的位置,当用户的输入无效时触发错误是很有用的。在 PHP 中,这个任务由 trigger_error() 函数完成。

实例

在本例中,如果 "test" 变量大于 "1",就会发生错误:

<?php
$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below");
}
?>
Copy after login

以上代码的输出如下所示:

Notice: Value must be 1 or below
in C:webfoldertest.php on line 6

您可以在脚本中任何位置触发错误,通过添加的第二个参数,您能够规定所触发的错误级别。

可能的错误类型:

E_USER_ERROR - 致命的用户生成的 run-time 错误。错误无法恢复。脚本执行被中断。
E_USER_WARNING - 非致命的用户生成的 run-time 警告。脚本执行不被中断。
E_USER_NOTICE - 默认。用户生成的 run-time 通知。在脚本发现可能有错误时发生,但也可能在脚本正常运行时发生。

在本例中,如果 "test" 变量大于 "1",则发生 E_USER_WARNING 错误。如果发生了 E_USER_WARNING,我们将使用我们自定义的错误处理程序并结束脚本:

1)
{
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
Copy after login

以上代码的输出如下所示:

Error: [512] Value must be 1 or below
Ending Script

现在,我们已经学习了如何创建自己的 error,以及如何触发它们,接下来我们研究一下错误记录。

错误记录

在默认的情况下,根据在 php.ini 中的 error_log 配置,PHP 向服务器的记录系统或文件发送错误记录。通过使用 error_log() 函数,您可以向指定的文件或远程目的地发送错误记录。

通过电子邮件向您自己发送错误消息,是一种获得指定错误的通知的好办法。

通过 E-Mail 发送错误消息

在下面的例子中,如果特定的错误发生,我们将发送带有错误消息的电子邮件,并结束脚本:

<?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);
}
?>
Copy after login

以上代码的输出如下所示:

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

接收自以上代码的邮件如下所示:

Error: [512] Value must be 1 or below

这个方法不适合所有的错误。常规错误应当通过使用默认的 PHP 记录系统在服务器上进行记录。

总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。

相关推荐: 

PHP操作MongoDB的方法及简单分析

PHP封装的MSSql操作类以及完整实例分析

PHP中子类重载父类的方法(parent::方法名)

The above is the detailed content of Usage and examples of PHP error handling functions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template