Php error handling, php Error

Source: Internet
Author: User
Tags php email php exception handling php form php json

Php error handling, php Error

In PHP, the default error handling is simple. An error message is sent to the browser. The message contains the file name, row number, and description error message.

  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:

  • 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 in C:webfoldertest.php on line 2

To prevent users from getting error messages similar to the preceding one, 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

Compared with the previous code, the above Code is more effective 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 up to 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 number. See the following table: Error Report level.
Error_message Required. Specifies an error message for a user-defined error.
Error_file Optional. Specifies the name of the file where an 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 handled by custom error handlers:

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 is found, but it may also 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. (In PHP 5.4, E_STRICT becomes 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 handling program

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 the 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 is as follows:

Error: [8] Undefined variable: test

 

Trigger Error

In the script, it is useful to trigger an error when user input is invalid. In PHP, this task is completed by the trigger_error () function.

Instance

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 is as follows:

Notice: Value must be 1 or belowin C:webfoldertest.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. An error may occur when the script is found, but it may also occur when the script runs normally.

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 is as follows:

Error: [512] Value must be 1 or belowEnding Script

Now we have learned how to create our own errors and how to trigger them. Next we will study error records.

  Error records

By default, according to The error_log configuration in php. ini, PHP sends error records to the server's 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 is as follows:

Error: [512] Value must be 1 or belowWebmaster has been notified

Emails from the above Code are as follows:

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.

 

Address: http://www.manongjc.com/php/php_error.html

Php-related reading materials:

  • Php date
  • PHP File Inclusion
  • PHP File
  • PHP File Upload
  • Php Cookies
  • Php Sessions
  • Php email
  • Php security email
  • Php error handling
  • PHP Exception Handling
  • Php Filter
  • PHP advanced Filter
  • Php json
  • Php form

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.