PHP simple error handling

Source: Internet
Author: User
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:/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:

<?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

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.