PHP Error Handling Instance method

Source: Internet
Author: User
Tags parse error php error php error reporting php script zend

1. PHP Error Default processing method

In PHP, the default error handling is simple. A message is sent to the browser with a file name, line number, and a message that describes the error. Error handling is an important part of creating scripts and Web applications. If your code lacks error detection coding, then the program looks unprofessional and opens the door to security risks.

2. Improved processing methods:

1. Simple "Die ()" statement

2. error_reporting (); Set the error level for PHP and return to the current level

3. Custom error and Error triggers

3. PHP Error Level:

1 E_error Fatal Run-time error. The error cannot be recovered. Execution of the script is paused

2 e_warning non-fatal run-time error. Execution of the script does not stop

4 E_parse Compile-time parse error. Parsing errors should only be generated by the parser

8 E_notice run time notification.

E_core_error fatal error when PHP is started. This is like a e_error in the PHP core

E_core_warning a non-fatal error when PHP is started. This is like a e_warning warning in PHP core

E_compile_error Fatal compile-time error. This is like a e_error generated by the Zend scripting engine

E_compile_warning non-fatal compile-time error, a e_warning warning generated by the Zend scripting engine

The e_user_error fatal user-generated error.

E_user_warning a non-fatal user-generated warning.

1024x768 E_user_notice user-generated notifications.

2048 e_strict enables PHP to modify code recommendations to ensure the best interoperability and forward compatibility of your code.

4096 E_recoverable_error catch a fatal error.

8191 E_all all errors and warnings.

4. PHP Error Reporting:

PHP does not turn on error reporting by default, there are two ways to prompt for errors:

1. Configure the php.ini file:

Change Display_errors =off to Display_errors = On

PHP defaults to show all errors, and some harmless hints we do not need to display, in addition to configure the error level: change error_reporting = E_all to: error_reporting= E_all & ~e_notice

Another: error echo, commonly used in development mode, but error echo can expose a lot of sensitive information, for attackers to facilitate the next attack. In a formal environment, it is recommended to turn off this option while Log_error=on, if an error occurs, the server is wrong, but the error message is not recorded in the log.

2. Add in the program

<?php  error_reporting (0);//Close error report  error_reporting (E_error | e_warning | E_parse); Report runtime error  error_reporting (e_all);//Report All Errors  error_reporting (E_all & ~e_notice);//Report all errors except E_notice ?>

5. Custom error handlers and error triggers

Custom Error Handler:

User_error_function (Error_level,error_message,error_file,error_line,error_context) (user-defined, used in Set_error_ called in handler)

Error_level: Required (Error level)

Error_message: Required (user-defined error-set error message)

Error_file,error_line,error_context: Optional (information such as the wrong file, line number, etc.)

Set_error_handler ():

If this function is used, the standard PHP error handler (error_reporting () will be invalidated) and, if necessary, the user-defined error handler must terminate (Die ()) script.

Set_error_handler () requires only one parameter (custom error handler), you can add a second parameter to define the error level.

Trigger_error () Trigger error

The location of the user input data in the script is useful for triggering errors when the user's input is not valid. 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 error types: E_user_error, e_user_warning, e_user_notic.

Example:

Custom error handler function MyErrorHandler ($errno, $errstr, $errfile, $errline) {if (!) (    Error_reporting () & $errno)) {return;}        Switch ($errno) {case E_user_error:echo <b>MyERROR</b> [$errno] $errstr <br/> ";        echo "Error line: $errline in file: $errfile <br/>"; echo "PHP version:". Php_version. " (" . Php_os. ")        <br/> ";    Break        Case E_user_warning:echo "<b>MyWARNING</b> [$errno] $errstr <br/>";    Break        Case E_user_notice:echo "<b>MyNOTICE</b> [$errno] $errstr <br/>";    Break        Default:echo "Unknown error type:[$errno] $errstr <br/>";    Break } return true; Test function Functiontrigger_test ($age) {if ($age <= 0| | $age > 999) trigger_error ("Age not valid: $age years old", e_user_error); if ($age <) Trigger_error ("Minors: $age years old", e_user_warning), if ($age > 40&& $age <) trigger_error ("older Large: $age years old ", E_user_notice);} If the error is handled simply and uniformly: $errorHandler = set_error_handler ("MyErrorHandler"); trigger_test (1000);//will throw an error level errors//If you want to handle different error levels separately, you need to construct different levels of error handler function Myerror ($errno, $errstr, $errfile, $errline) {//Specific methods}function mywarning ($errno, $errstr, $errfile, $errline) {//specific Method}function Myntice ($errno, $errstr, $errfile, $errline) {//Specific treatment Method}set_error_handler (' Myerror ', e_user_error); set_ Exception_handler (' mywarning ', e_user_warning); Set_exception_handler (' Myntice ', e_user_notice); Trigger_error (' Intentionally throws a mistake, is still very serious which kind of! ', e_user_error);

6. Block PHP Error hints

Method One:

Add @ before a function that is likely to go wrong, and then or Die ("")

such as: @mysql_connect (...) or Die ("Database Connect Error")

Note: @ In fact it is the error suppressor, that is, even if an error occurs, ignore the error message, continue to execute the following code, the advantage is not to output an error message.

Or die When you call the Die () and exit () in the script, the entire script is terminated. They can all be used to prevent the script from continuing, leaving some important operations, such as establishing a database connection, from occurring. You can also pass a string that will be printed in the browser to Die () and exit ().

Method Two:

Edit PHP.ini, will "Display_errors =off" while will log_error=on, error_log =/var/log/php-error.log

Method Three:

Add error_reporting (0) before the php script to block all error prompts.
Among them, error_reporting configures the level of return for error messages.
Syntax: int error_reporting (int [level]);
return value: Integer
Function type: PHP system function

Related recommendations:

PHP error Handling method instance

PHP Error Handling and logging

PHP error Handling method Summary _php Tutorial

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.