Error handling is a very important part of creating web applications. If your code is not efficient, then you may receive error messages. Also, it will put your application in a risky position. Let us examine some methods of dealing with errors in PHP.
Default Error Handling in PHP
By default, error handling in PHP is quite simple. An error message along with line number, file name and a message is sent to the web browser.
Error Handling Methods:
Following are the error handling methods:
1.Basic Error Handling Using die() statements
Consider the following example in which we are trying to open a file which doesn’t exist in htdocs folder.
Example
<?php $file=fopen("welcome.txt","r"); ?>
Output
Warning: fopen(welcome.txt): failed to open stream: No such file or directory in C:\xampp\htdocs\test.php on line 2
Solution
Use the following code containing die() . If file doesn’t exist then it will show error.
Code
<?php if(!file_exists("welcome.txt")) { die("File not found"); } else { $file=fopen("welcome.txt","r"); } ?>
Output
File not found
The way we dealt with the earlier code is not always the preferred approach, but a simpler method in which we use a straight forward error mechanism. Hence, an alternative approach for handling errors are the PHP functions.
2.Error Reporting
Here we will see that How to Create a Custom Error Handler in PHP
A custom error handler is basically a special function which is called when an event occurs or says error occurs.
Syntax
Error_function(error_level,error_message,error_file,error_line,error_context)
This function handles at least 2 parameters, namely error level, and error message. The other three parameters are optional. Description of these parameters is as follows:
Error_level | It is a compulsory parameter. It specifies the error report level. It should be a numeric value. |
Error_message | Required. Specifies the error message for the user-defined error
It is also mandatory parameter. It determines the error message for the user defined errors. |
Error_file | It is an optional parameter. It shows the file name in which the error has occurred. |
Error_line | It is also an optional field. It specifies the line numbers of the lines in which error has occurred. |
Error_context | It is also optional. Here you may specify the array which contains variables and values at the time of error occurring. |
What Are Error Report Levels?
User defined error handler can be used to report different types of error. Let’s have a look on the list of error report levels:
E_Warning | It shows non-fatal run time errors. It doesn’t stop execution of the script. |
E_Notice | They are basically run time notices. They are displayed when there is some error within the script. |
E_USER_ERROR | It is a user generated error. It is similar to E_ERROR and trigger_error() |
E_USER_WARNING | It is a typical non-fatal warning which is user generated. It is similar to E_WARNING. |
E_USER_NOTICE | It is also a user generated notice. Likewise it is similar to E_Notice. |
E_RECOVERABLE_ERROR | It is a catchable fatal error. It is similar to E_ERROR with the difference that it can be fixed using user defined handle. |
E_ALL | It will deal with every warning and error. |
3.Custom Errors & Triggers
Handling of Errors by Creating Custom Function
We will now create a user defined function to handle errors. Now lets create a function to handle errors:
function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr<br>"; echo "Ending Script"; die(); }
When the above code is triggered, it shows an error message with the error level. It then displays them and halts the script execution. We have just created an error handling function. Now we have to finalize when it should be triggered.
How to Set Error Handler?
In PHP, we have a built-in error handler. We will now make our function the default error handler. It is also possible that we can change the error handler occurrence specific to a few errors. But for now, we will use custom error handler for all errors.
Set_error_handler(“customError”);
Since we want our custom function to handle all errors, the set_error_handler() only needed one parameter, a second parameter could be added to specify an error level.
Let’s consider the example below, where we are testing the error handler. We are trying to display such a variable in this example which actually doesn’t exist.
Code
Testing the error handler by trying to output variable that does not exist:
<?php //error handler function function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr"; } //set error handler set_error_handler("customError"); //trigger error echo($test); ?>
Output
Error: [8] Undefined variable: test
Trigger an Error
Its significance is when users can input data so that errors are triggered when an illegal input occurs. We have a predefined function in php for this purpose called trigger_error().
Example
Lets consider the example below, in this case if test is bigger than 1, it will trigger the error.
<?php $test=2; if ($test>1) { trigger_error("Value must be 1 or below"); } ?>
Output
Notice: Value must be 1 or below in C:\xampp\htdocs\test.php on line 5
These errors can be triggered wherever you feel necessary to trigger.
Example
Let’s consider another example in which if a test variable is bigger than 1, then E_USER_WARNING occurs. If it happens, then a custom error handler is utilized.
<?php //error handler function function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr<br>"; 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); } ?>
Output:
Error: [512] Value must be 1 or below
Ending Script
4. Error Reporting
Up till now, we have covered errors triggering and custom errors handling. Let’s start our next topic, Error Logging.
Error Logging
In PHP, error log is sent to the logging system of the server. It is also dependent on php.ini file. Luckily, we have a predefined function in PHP for this purpose called error_log().
By using this function, you may send error logs to a remote destination. Many developers find this a good way to send error messages by email to themselves. Hence, they get notified in this way.
Send an Error Message by E-Mail
In the example below, we will send email with error message. In case the error occurs, it will end the script.
<?php //error handler function function 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 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); } ?>
Output
Error: [512] Value must be 1 or below
Webmaster has been notified.
At the specified email address, the email will be received as below:
Error: [512] Value must be 1 or below
It should be noted that regular errors should be logged by using default logging system. It is not a good approach to adopt with all errors.
Errors and Logging
Let’s consider the errors and their descriptions about logging.
E_ERROR | They are fatal errors which occur at run time. As a result of such errors, execution of the script is stopped. These type of errors most commonly occur due to memory allocation type problems. |
E_WARNING | They are also runtime warnings but they never cause halting of execution of script. |
E_PARSE | They are generated by the parser. They occur at compile time mostly. |
E_NOTICE | They also at run time. They are run time notices. |
E_CORE_ERROR | They are fatal errors which usually occur during the startup. They are similar to E_ERROR with a difference that it is generated by core PHP. |
E_CORE_WARNING | It is similar to E_WARNING. These are the warnings of non fatal errors. These warnings also occur at the time of startup. It is also generated by core PHP. |
E_COMPILE_ERROR | They are similar to E_ERROR. They are basically fatal errors which occurs at compile time. Difference between this and E_ERROR is that it is generated by Zend Engine. |
E_COMPILE_WARNING | They are non fatal errors, or say compile time warnings. It is similar to E_WARNING but with a difference that it is generated by Zend engine. |
E_USER_ERROR | They are user generated error messages. It is similar to E_ERROR with a difference that It is generated by PHP function trigger_error(). |
E_USER_WARNING | They are warning messages generated by users. It is similar to E_WARNING with a difference that it is also generated by trigger_error() function. |
E_USER_NOTICE | User-generated notice message. This is like an E_NOTICE, except it is generated in PHP code by using the PHP function trigger_error(). |
E_STRICT | You should enable this to get suggestions by PHP . It will definitely lead to best compatibility of your code. |
E_DEPRECATED | They are run time notices. By enabling this, you may receive warnings which will not work in future versions. |
E_RECOVERABLE_ERROR | It is a fatal error which is catchable. It is an indication of a typical serious error. |
E_USER_DEPRECATED | These are the warning messages generated by the user. It is much similar to E_DEPRECATED but with a difference that it is generated by function trigger_error() |
Well, I hope you found this post on PHP error handling useful. If you’re confused about anything discussed here, or you’ve got a comment, fire away. I’d love to discuss PHP error handling with you 🙂