Today we will study how to handle errors in the PHP script in this Error Handling in PHP tutorial.
- In any stand alone or web based application error handling is the very important task that to be done. If error handling is not done, many such system generated messages will be displayed on the occurrence of errors which take a long time to understand. And it will be the proof of the laziness of the programmer who did not take measures to handle these errors.
- It is always a good practice of not showing raw errors to the user. The error messages should always be in a simple and friendly language, easy to understand.
- There are different methods to find out errors and handle them.
- Let us go through a very simple and basic error handling method that uses a die() function.
Use of die() function:
- The function die() is used to output an error message when an error is encountered.
- The system error message might be big and difficult to understand. This error message is suppressed and the message given in the die() function is displayed.
- Let us have an example to demonstrate die() function.
- For demonstration create a new folder named error_handling in the htdocs folder in xampp folder in C drive. Then open a new notepad++ document and save it as index.php in the newly created error_handling folder.
- The code is given below:
<html> <head> <title>Error Handling in PHP</title> </head> <body> <h1>Demonstration of die()</h1> <?php $fp=fopen("one.txt","r"); ?> </body> </html>
$fp=fopen("one.txt","r");
<html> <head> <title>Error Handling in PHP</title> </head> <body> <h1>Demonstration of die()</h1> <?php //$fp=fopen("one.txt","r"); if(!file_exists("one.txt")) die("<br><strong>one.txt file does not exist.</strong>"); else { $fp=fopen("one.txt","r"); while(!feof($fp)) { echo $gets."<br>"; } } ?> </body> </html>
Custom errors and error triggers:
In this method the error functions are created and triggered whenever error occurs. A step by step procedure to use it is given below:
- Creation of custom error handler:
- We can use die() to handle errors, but we can make the error messages more creative just like the system error messages by providing the type of error, error message, file in which the error occurred by defining a error function.
- This function can have in total 5 parameters of which 2 are basic and mandatory and the other 3 are optional.
- This function is a custom error function and should be able to handle at least 2 parameters.
- Syntax of custom error function is:
- All the parameters are explained below:
- error_level: Required. Specifies the error reporting level for the error.
- error_message: Required. Specifies the error message.
- error_file: Optional. Specifies the name of the file in which the error occurred.
- error_line: Optional. Specifies the line number at which the error occurred.
- error_context: Optional. Specifies an array containing every variable in the scope where the error occurred.
- The error_level parameter contains certain constant values that allow the error to be presented as a warning, fatal error etc.
- One of these constants can be used as the value for error_level parameter of the error function.
- The table below shows the constants with their description:
- Let us write the error_function:
- Write the following code in index.php page:
- Here we have defined an error function with name custom_error. This function has 2 parameters, one is the level of error and the other is the error message.
- Values of these parameters are displayed using an echo function.
- But the values will be passed to the function custom_error, only when it is called.
- So for time being, the function custom_error() will stay idle.
- Setting the error handler:
- There is a default built in error handler in PHP which handles all the errors.
- But we have a function custom_error() ready with us and we want it to handle all the errors.
- Our custom_error() function will be allowed to handle all the errors by setting it as the default error handler using set_error_handler() function.
- The task of set_error_handler() function is to allow the function passed to it as a parameter to become a default error handler.
- It is shown in the following code. The code of just one line is added to the code written for point number 1 as shown below:
- Here, the set_error_handler(“custom_error”); statement is added to the existing code.
- This sets the custom_error() function as the default error handler.
- Triggering an error:
- To trigger an error the function trigger_error() is used.
- Let us try our first example.
- Let us try accessing a non-existent file. Here as the file does not exist, we will have to trigger an error message.
- Write the following code in index.php page:
- In the above code we have completed the whole task of handling errors.
- We have defined the error function custom_error() which will be called when the error is triggered using trigger_error() function.
- After defining the custom_error() function, it is set as the default error handler function using the set_error_handler() function.
- Then we tried to open a file user.txt in the read mode. If this file exists, its contents will be displayed on the browser. But if it does not exist, an error will be triggered using trigger_error() function.
- In our case, the file user.txt does not exist. So an error is triggered using trigger_error() function as shown below:
- Here, we have passed an error message and the error level E_USER_WARNING.
- This trigger_error() function passes the values to the parameters in custom_error() function which is set as the default error handler function.
- In custom_error() function the values assigned to the parameters are displayed using echo statement.
- The error level code is displayed as 512.
- The output is shown below:
error_function(error_level,error_message,error_file,error_line,error_context);
CONSTANT | DESCRIPTION |
---|---|
E_ERROR | It is a fatal run-time error where execution of the script is halted. this indicates errors that cannot be recovered from problems like memory allocaton problems, etc. |
E_WARNING | It is a run-time warning (a non-fatal error). Execution of the script is not halted. |
E_NOTICE | It is a run-time notice.It indicates that the script encountered something that could indicate an error, but may also happen normally. |
E_DEPRECATED | Run-time notices that warn about code that will not work in future. |
E_STRICT | Run-time notices that suggest changes to your code which will ensure best interoperability and forward compatibility with future versions of PHP. |
E_USER_ERROR | It is a user generated error message.This is like an E_ERROR,except it is generated usign trigger_error() function in PHP. |
E_USER_WARNING | It is a user generated warning message.This is like an E_WARNING,except it is generated usign trigger_error() function in PHP. |
E_USER_NOTICE | It is a user generated notice.This is like an E_NOTICE,except it is generated usign trigger_error() function in PHP. |
E_USER_DEPRECATED | It is a user generated notice.This is like an E_EPRECATED,except it is generated usign trigger_error() function in PHP. |
E_ALL | Enables all PHP Errors and warnings(except E_STRICT in ver<5.4) |
table 1
<html> <head> <title>Error Handling in PHP</title> </head> <body> <h1>Demonstration of custom error function</h1> <?php function custom_error($elevel,$emsg) { echo "ERROR:".$elevel." --> ".$emsg; } ?> </body> </html>
Now our custom error handler is ready.
<html> <head> <title>Error Handling in PHP</title> </head> <body> <h1>Demonstration of custom error function</h1> <?php //error handler function function custom_error($elevel,$emsg) { echo "ERROR:".$elevel." --> ".$emsg; } //setting the error handler function set_error_handler("custom_error"); ?> </body> </html>
Now next step is to trigger an error, if such errornous condition occurs.
<html> <head> <title>Error Handling in PHP</title> </head> <body> <h1>Demonstration of custom error function</h1> <?php //error handler function function custom_error($elevel,$emsg) { echo "ERROR: ".$elevel." --> ".$emsg; } //setting the error handler function set_error_handler("custom_error"); //accesing a file to read if(!file_exists("user.txt")) trigger_error("<strong>The file does not exist.</strong>",E_USER_WARNING); else { $fp=fopen("one.txt","r"); while(!feof($fp)) { echo $gets."<br>"; } } ?> </body> </html>
trigger_error("<strong>The file does not exist.</strong>",E_USER_WARNING);
Thus we learned to handle errors using function die() and custom error handling function. This will be very convenient because we just have to write the function once, set it as the default error handler and trigger the error wherever required.
Thus completed our Error handling in PHP tutorial.