PHP error handling

Source: Internet
Author: User
Tags php error
ArticleDirectory
    • Syntax
    • Error Report Level
    • Instance
    • Example
    • Possible error types:
    • Example
    • Send error messages via email
    • Syntax

Introduction: This is a detailed page for PHP error handling. It introduces PHP related knowledge, skills, experience, and some PHP source code.

Class = 'pingjiaf' frameborder = '0' src = 'HTTP: // biancheng.dnbc?info/pingjia.php? Id = 357750 'rolling = 'no'> PHP error handling

Create scripts and Web applicationsProgramError handling is an important part. If yourCodeThe absence of error detection code makes the program seem unprofessional and opens 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 for you:

    • Simple "Die ()" Statement
    • Custom errors and error triggers
    • Error Report
Basic Error Handling: Use the die () function

The first example shows a simple script for opening a text file:

 
<? 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 inC: \ webfolder \ test. phpOn Line2

To prevent users from getting error messages similar to the above, we can check whether the file exists before accessing the file:

 
<? Phpif (! 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 similar to this:

 
File not found

The above code is more effective 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 proper method. Let's look at the alternative PHP functions used to handle errors.

Create a custom error Processor

It is very easy to create a custom error processor. We have created a dedicated function that can be called when an error occurs in PHP.

This function must be able to process at least two parameters (error level and error message), but can accept a maximum of 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 report level for user-defined errors. It must be a value.

See the following table: Error Report level.

Error_message Required. Specifies an error message for a user-defined error.
Error_file Optional. Specifies the file name in which the error occurs.
Error_line Optional. Specifies the row number of the error.
Error_context Optional. Define an array that contains each variable and their values when an error occurs.
Error Report Level

These error reporting levels are different types of errors that the error handler aims to handle:

Value Constant Description
2 E_warning Non-fatal run-time error. Do not pause script execution.
8 E_notice

Run-time notification.

An error may occur when the script runs normally.

256 E_user_error Fatal user-generated error. This is similar to the 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 notifications. This is similar to the e_notice set by the programmer using the PHP function trigger_error.
4096 E_recoverable_error Possible fatal errors. Similar to e_error, but can be captured by a user-defined handler. (See set_error_handler ())
8191 E_all

All errors and warnings except level e_strict.

(In PHP 6.0, e_strict is part of e_all)

Now, let's create a function to handle errors:

Function customerror ($ errno, $ errstr) {echo "<B> error: </B> [$ 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 outputs the error level and message and terminates the script.

Now we have created an error handling function. We need to determine when to trigger this function.

Set error handler

The default PHP error handler is a built-in error handler. We plan to transform the above function into the default error handler during script running.

You can modify the error handler so that it can only be applied to some errors, so that the script can handle different errors in different ways. However, in this example, we intend to use our custom error handler for all errors:

 
Set_error_handler ("customerror ");

Because we want our custom function to handle all errors, set_error_handler () only requires one parameter. You can add the second parameter to specify the error level.

Instance

Test the error handler by outputting a non-existent variable:

 
<? PHP // error handler functionfunction customerror ($ errno, $ errstr) {echo "<B> error: </B> [$ errno] $ errstr ";} // set error handlerset_error_handler ("customerror"); // trigger errorecho ($ test);?>

The output of the above Code should be similar to the following:

Error: [8] undefined variable: Test
Trigger Error

The location where the user inputs data in the script. It is useful to trigger errors when the user inputs are invalid. In PHP, this task is completed by trigger_error.

Example

In this example, if the "test" variable is greater than "1", an error occurs:

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

The output of the above Code should be similar to the following:

 
Notice: value must be 1 or belowin c: \ webfolder \ test. php on line 6

You can trigger an error at any position in the script. By adding the second parameter, you can specify the trigger error level.

Possible error types:
    • E_user_error-fatal User-Generated run-time error. The error cannot be recovered. Script Execution is interrupted.
    • E_user_warning-Run-Time Warning generated by non-fatal users. Script execution is not interrupted.
    • E_user_notice-default. User-Generated run-time notification. A possible error is found in the script, or it may occur when the script runs 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:

<? PHP // error handler functionfunction customerror ($ errno, $ errstr) {echo "<B> error: </B> [$ errno] $ errstr <br/> "; echo "ending script"; die () ;}// set error handlerset_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 the following:

 
Error: [512] value must be 1 or belowending script

Now we have learned how to create our own errors and how to punish them. Now let's look at the error records.

Error records

By default, according to The error_log configuration in PHP. ini, PHP sends an error record to the server's error record system or file. By using the error_log () function, you can send error records to specified files or remote destinations.

An error message is sent to you by email, which is a good way to receive notification of a specified error.

Send error messages via email

In the following example, if a specific error occurs, we will send an email with an error message and end the script:

<? PHP // error handler functionfunction 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 handlerset_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 the following:

 
Error: [512] value must be 1 or belowwebmaster has been notified

Emails received from the code above are similar to the following:

 
Error: [512] value must be 1 or below

This method is not suitable for all errors. Regular errors should be recorded on the server by using the default PHP record system.

Error backtracking

Definition and usage

The PHP debug_backtrace () function generates a backtrace.

This function returns an associated array. The following elements may be returned:

Name Type Description
Function String The current function name.
Line Integer The current row number.
File String The current file name.
Class String Current Class Name
Object Object Current object.
Type String The current call type. Possible calls:

  • Return Value: "->"-method call
  • Return Value: ":"-static method call
  • Return nothing-function call
ARGs Array If function parameters are listed. If the referenced file lists the referenced file names.
Syntax
 
Debug_backtrace ()
Example
<? Phpfunction 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 (=> C: \ webfolder \ test. PHP [Line] => 7 [function] => three [ARGs] => array ([0] => Cleveland [1] => brown )) [1] => array (=> C: \ webfolder \ test. PHP [Line] => 3 [function] => two [ARGs] => array ([0] => Glenn [1] => Quagmire )) [2] => array (=> C: \ webfolder \ test. PHP [Line] => 14 [function] => one [ARGs] => array ([0] => Peter [1] => Griffin )))

From: http://www.w3school.com.cn/php/php_error.asp

Love J2EE follow Java Michael Jackson video station JSON online tools

Http://biancheng.dnbcw.info/php/357750.html pageno: 2.

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.