search
HomeBackend DevelopmentPHP TutorialPHP error handling experience sharing

This tutorial covers some of the most important error detection methods in PHP.

We will explain you different error handling methods:

Simple "die()" statement
Custom errors and error triggers
Error reporting
Basic error handling: using the die() function
First example Shows a simple script to open a text file:
Copy code The code is as follows:
$file=fopen("welcome.txt","r");
?>

If the file does not exist, you You will get errors 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 like the above Error message, we check whether the file exists before accessing it:
Copy code The code is as follows:
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 the 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)

PHP error handling experience sharing

Error reporting levels

These error reporting levels are the different types of errors that error handlers are designed to handle:

PHP error handling experience sharing

Now, let’s create a function that handles errors:
Copy code The code is as follows:
function customError($errno, $errstr)
{
echo "Error: [$errno] $errstr< ;br />";
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 trigger the function.
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, only one set_error_handler() is needed Parameter, you can add a second parameter to specify the error level.

Example
Test this error handler by trying to output a variable that does not exist:
Copy code The code is as follows:
//error handler function
function customError($errno, $errstr)
{
echo "Error: [$errno] $errstr";
}

//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 an error
In the script where the user inputs data, it is useful to trigger 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:
Copy code The code is as follows:
$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 an error anywhere in the script, and 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 E_USER_WARNING occurs, we will use our custom error handler and end the script:
Copy code The code is as follows:
//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 that we have learned how to create our own errors and how to punish them, let’s study error logging.
Error Logging
By default, according to the error_log configuration in php.ini, PHP sends error records to the server's error logging system or file. By using the error_log() function, you can send error records to a specified file or remote destination.

Sending an error message to yourself via email 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:
Copy code The code is as follows:
/ /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 notified The email received from the above code is 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
PHP debug_backtrace() function generates a backtrace.

This function returns an associative array. The following are the elements that may be returned:

PHP error handling experience sharing

Syntax
debug_backtrace() example
Copy code The code is as follows:
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");
?>

Output:

Array
(
[0] => Array
(
[file] => C:webfoldertest. php
[line] => 7
[function] => three
[args] => ] => Array
(
[file] => C:webfoldertest.php
[line] => 3
[function] => two
[args] => > Glenn
[1] => Quagmire
)
)
[2] => Array
(
[file] => C:webfoldertest.php
[line] => 14
[function] = > one
[args] => Array
(
[0] => Peter
[1] => Griffin
)
)
)

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
Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

Explain Fibers in PHP 8.1 for concurrency.Explain Fibers in PHP 8.1 for concurrency.Apr 12, 2025 am 12:05 AM

Fibers was introduced in PHP8.1, improving concurrent processing capabilities. 1) Fibers is a lightweight concurrency model similar to coroutines. 2) They allow developers to manually control the execution flow of tasks and are suitable for handling I/O-intensive tasks. 3) Using Fibers can write more efficient and responsive code.

The PHP Community: Resources, Support, and DevelopmentThe PHP Community: Resources, Support, and DevelopmentApr 12, 2025 am 12:04 AM

The PHP community provides rich resources and support to help developers grow. 1) Resources include official documentation, tutorials, blogs and open source projects such as Laravel and Symfony. 2) Support can be obtained through StackOverflow, Reddit and Slack channels. 3) Development trends can be learned by following RFC. 4) Integration into the community can be achieved through active participation, contribution to code and learning sharing.

PHP vs. Python: Understanding the DifferencesPHP vs. Python: Understanding the DifferencesApr 11, 2025 am 12:15 AM

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 It Dying or Simply Adapting?PHP: Is It Dying or Simply Adapting?Apr 11, 2025 am 12:13 AM

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The Future of PHP: Adaptations and InnovationsThe Future of PHP: Adaptations and InnovationsApr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.