PHP Error handling experience sharing _php tips

Source: Internet
Author: User
Tags php error terminates
This tutorial introduces some of the most important error detection methods in PHP.

We will explain the different error handling methods for 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 that opens a text file:
Copy Code code as follows:

<?php
$file =fopen ("Welcome.txt", "R");
?>

If the file does not exist, you will get an error similar to this:

Warning:fopen (Welcome.txt) [function.fopen]: failed to open stream:
No such file or directory in C:\webfolder\test.php on line 2 to prevent users from getting similar error messages, we detect the existence of the file before accessing the file:
Copy Code code as follows:

<?php
if (!file_exists ("Welcome.txt"))
{
Die ("File not Found");
}
Else
{
$file =fopen ("Welcome.txt", "R");
}
?>

Now, if the file doesn't exist, you get an error message like this:

File not found is more efficient than previous code because it employs a simple error-handling mechanism that terminates the script after the error.

However, simply terminating the script is not always the right approach. Let's look at the alternate PHP functions for handling errors.
Creating custom Error Handlers
Creating a custom error handler is simple. We have simply created a private function that can be called when an error occurs in PHP.

The function must be capable of handling at least two parameters (Error level and error message), but can accept up to five parameters (optional: File, Line-number, and error context):

Grammar
Error_function (Error_level,error_message,
Error_file,error_line,error_context)
Parameters Description
Error_level

Necessary. Sets the error reporting level for user-defined errors. Must be a number of values.

See table below: Error reporting level.

Error_message Necessary. Specify error messages for user-defined errors.
Error_file Optional. Specify the name of the file in which the error occurred.
Error_line Optional. The line number that sets the error to occur.
Error_context Optional. Specify an array that contains each variable that was used when the error occurred and their values.

Error Reporting level

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

value Constants Description
2 E_warning Non-fatal run-time error. Script execution is not paused.
8 E_notice

Run-time notice.

The script found that an error might occur, but it may also occur when the script is running correctly.

256 E_user_error Fatal user-generated error. This is similar to the e_error that programmers use PHP function Trigger_error () settings.
512 E_user_warning A non-fatal user-generated warning. This is similar to the e_warning that programmers use PHP function Trigger_error () settings.
1024 E_user_notice User-generated notifications. This is similar to the e_notice that programmers use PHP function Trigger_error () settings.
4096 E_recoverable_error A fatal error that can be caught. Similar to E_error, but can be captured by user-defined handlers. (see Set_error_handler ())
8191 E_all

All errors and warnings, except for level e_strict.

(In PHP 6.0,e_strict is part of E_all)

Now, let's create a function that handles the error:
Copy Code code as follows:

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

The code above is a simple error-handling function. When it is triggered, it gets the error level and error message. It then prints out the error level and message and terminates the script.

Now that we have created an error-handling function, we need to determine when the function is triggered.
Set Error Handler
The default error handler for PHP is a built-in error handler. We intend to transform the above function into the default error handler during the script run.

You can modify the error handler so that it applies only to certain errors, so that the script can handle different errors in different ways. In this case, however, we intend to use our custom error handlers for all errors:

Set_error_handler ("Customerror"); because we want our custom function to handle all errors, Set_error_handler () only needs one argument, and the second parameter can be added to specify the error level.

Instance
Test this error handler by trying to output a variable that does not exist:
Copy Code code as follows:

<?php
Error handler function
function Customerror ($errno, $ERRSTR)
{
echo "<b>Error:</b> [$errno] $errstr";
}

Set Error Handler
Set_error_handler ("Customerror");

Trigger Error
Echo ($test);
?>

The output of the above code should look like this:

Error: [8] Undefined Variable:test trigger Error
The location where the user enters data in the script is useful for triggering errors when the user's input is invalid. In PHP, this task is done by Trigger_error ().

Example
In this case, if the "test" variable is greater than "1", an error occurs:
Copy Code code as follows:

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

The output of the above code should look like this:

Notice:value must be 1 or below
In C:\webfolder\test.php on line 6 You can trigger an error anywhere in the script, and by adding a second parameter, you can specify the level of error that is triggered.

Possible types of errors:
E_user_error-Fatal user-generated run-time error. The error cannot be recovered. Script execution was interrupted.
E_user_warning-a 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, or it may occur when the script is running normally.
Example
In this case, if the "test" variable is greater than "1", a e_user_warning error occurs. If e_user_warning happens, we'll use our custom error handler and end the script:
Copy Code code as follows:

<?php
Error handler function
function Customerror ($errno, $ERRSTR)
{
echo "<b>Error:</b> [$errno] $errstr <br/>";
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: [i] Value must be 1 or below
Ending script now, we've learned how to create our own error, and how to punish them, and now we're going to look at the error records.
Error logging
By default, PHP sends an error record to the server's error recording system or file, based on the Error_log configuration in php.ini. By using the Error_log () function, you can send error records to the specified file or remote destination.

Sending an error message to yourself by e-mail is a good way to get a notification of a specified error.

Send an error message via e-mail
In the following example, if a specific error occurs, we will send an email with an error message and end the script:
Copy Code code as follows:

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

The output of the above code should look like this:

Error: [i] Value must be 1 or below
Webmaster has been notified receive messages from the above code like this:

Error: [i] Value must be 1 or below this method does not apply to all errors. General errors should be logged on the server by using the default PHP recording system.

Error backtracking


Definitions and usage
The PHP debug_backtrace () function generates a backtrace.

The function returns an associative array. The following are the elements that can be returned:
name type Description
function String The current function name.
Line Integer The current line number.
File String The current file name.
Class String The current class name
Object Object The current object.
Type String The current invocation type, possible calls:
  • Back: "->"-Method call
  • Back to::-static method call
  • Return Nothing-function call
Args Array If you are in a function, list the function arguments. If you are referencing a file, list the names of the referenced files.
Grammar
Debug_backtrace () example
Copy Code code as follows:

<?php
function One ($str 1, $str 2)
{
Two ("Glenn", "quagmire");
}
function two ($str 1, $str 2)
{
Three ("Cleveland", "Brown");
}
Function three ($str 1, $str 2)
{
Print_r (Debug_backtrace ());
}

One ("Peter", "Griffin");
?>

Output:

Array
(
[0] => Array
(
[File] => C:\webfolder\test.php
[Line] => 7
[Function] => three
[Args] => Array
(
[0] => Cleveland
[1] => Brown
)
)
[1] => Array
(
[File] => C:\webfolder\test.php
[Line] => 3
[function] => two
[Args] => Array
(
[0] => Glenn
[1] => Quagmire
)
)
[2] => Array
(
[File] => C:\webfolder\test.php
[Line] => 14
[Function] => one
[Args] => Array
(
[0] => Peter
[1] => Griffin
)
)
)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.