search
HomeBackend DevelopmentPHP TutorialUsage and examples of PHP error handling functions

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");
?>

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");
}
?>

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)


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

错误报告级别

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

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

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

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

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


Value Constant Description
2 E_WARNING Non-fatal run-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 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)


设置错误处理程序

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

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

set_error_handler("customError");

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

实例

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

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

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

Error: [8] Undefined variable: test

触发错误

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

实例

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

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

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

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

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

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

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

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!

Statement
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
How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

How does using HTTPS affect session security?How does using HTTPS affect session security?Apr 22, 2025 pm 05:13 PM

HTTPS significantly improves the security of sessions by encrypting data transmission, preventing man-in-the-middle attacks and providing authentication. 1) Encrypted data transmission: HTTPS uses SSL/TLS protocol to encrypt data to ensure that the data is not stolen or tampered during transmission. 2) Prevent man-in-the-middle attacks: Through the SSL/TLS handshake process, the client verifies the server certificate to ensure the connection legitimacy. 3) Provide authentication: HTTPS ensures that the connection is a legitimate server and protects data integrity and confidentiality.

The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

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: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor