Home >Backend Development >PHP Tutorial >PHP 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)
Error reporting levels
These error reporting levels are the different types of errors that error handlers are designed to handle:
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:
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
)
)
)