[Php] PHP error handling

Source: Internet
Author: User
[Php] PHP error handling

Error handling is an important part when creating scripts and web applications. If your code lacks the error detection code, the program looks 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:

Custom error and error trigger error reports for simple "die ()" statements

Basic error handling: Use the die () function

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

$ 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 error messages similar to the above, we can check whether the file exists before accessing the file:

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 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"Error:[$ Errno] $ errstr
";

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:

// 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 the following:

Custom 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:

$ 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 below

In 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:

// 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 be similar to the following:

Error: [512] Value must be 1 or below

Ending 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:

// 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 the following:

Error: [512] Value must be 1 or below

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

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.