Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

PHP error handling


May 11, 2021 PHP


Table of contents


PHP error handling

There are also errors when using PHP, so how do we deal with them? Here's what's in this section.

In PHP, the default error handling is simple. An error message is sent to the browser with the file name, line number, and a message describing the error.


PHP error handling

Error handling is an important part of creating scripts and Web applications. If your code lacks error detection code, the program looks unsothy and opens the door to security risks.

This tutorial describes some of the most important error detection methods in PHP.

We'll show you the different ways to handle errors:

  • A simple "die()" statement
  • Custom errors and error triggers
  • Error reporting

Basic error handling: Use the die() function

The first example shows a simple script that opens a text file:

 <?php
 $file=fopen("welcome.txt","r");
 ?> 

If the file doesn't exist, you get an error like 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 one above, we detect the existence of a file before accessing it:

<?php
 if(!file_exists("welcome.txt"))
 {
 die("File not found");
 }
 else
 {
 $file=fopen("welcome.txt","r");
 }
 ?> 

Now, if the file doesn't exist, you get an error message like this:

File not found

The above code is more efficient 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 right way. Let's look at the alternative PHP function for handling errors.


Create a custom error processor

Creating a custom error processor is simple. We simply created a dedicated function that can be called in the event of an error in PHP.

The function must be able to handle at least two arguments (error level and error message), but can accept up to five parameters (optional: file, line-number, and error context):

Grammar

error_function(error_level,error_message,
error_file,error_line,error_context)

parameter describe
error_level Required.Error report level for user-defined errors.Must be a number.See the table below: Error report level.
error_message Required.Error message for user-defined errors.
error_file Optional.Specify the file name that the error occurred.
error_line Optional.Specifies the line number of the error.
error_context Optional.A array contains each variable that is used when an error occurs and their value.

Error reporting level

These error reporting levels are different types of errors handled by user-defined error handlers:

value constant describe
2 E_WARNING Non-fatal Run-Time errors.Do not suspend script execution.
8 E_NOTICE Run-Time notification.When the script discovery may have an error, it may also occur when the script is running normally.
256 E_USER_ERROR Fatal user generated errors.This is similar to the programmer using the PHP function trigger_error () settings set.
512 E_USER_WARNING Non-fatal users generated warnings.This is similar to the programmer using the E_WARNING set by the PHP function trigger_error ().
1024 E_USER_NOTICE The notification of the user generated.This is similar to the programmaker using the PHP function trigger_error () setting E_NOTICE.
4096 E_RECOVERABLE_ERROR Captuable fatal mistakes.Similar to E_ERROR, but can be captured by 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 code above is a simple error handler. W hen it is triggered, it gets an error level and an error message. It then outputs the error level and message, and terminates the script.

Now that we've created an error handler, we need to determine when to trigger it.


Set up an error handler

PhP's default error handler is the built-in error handler. We intend to transform the above function into the default error handler during script run.

You can modify the error handler so that it applies only to certain errors, so that the script can handle different errors in different ways. However, in this case, we intend to use our custom error handler for all errors:

set_error_handler("customError");

Since we want our custom functions to handle all errors, set_error_handler() requires only one argument, which can be added to specify the error level.

Test this error handler by trying to output variables that do 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);
 ?> 

The output of the above code looks like this:

Error: [8] Undefined variable: test


The error was triggered

Where the user enters the data in the script, it is useful to trigger an error when the user's input is invalid. In PHP, this task is done by trigger_error() function.

In this case, 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 looks like this:

Notice : Value must be 1 or below
in C:webfoldertest.php on line 6

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 types of errors:

  • E_USER_ERROR - Fatal user-generated run-time error. T he error could not be recovered. Script execution was interrupted.
  • E_USER_WARNING - a non-fatal user-generated run-time warning. S cript execution is not interrupted.
  • E_USER_NOTICE - Default. U ser-generated run-time notifications. This can happen when the script finds that there may be an error, but it can also occur when the script is working properly.

In this case, if the "test" variable is greater than "1", a E_USER_WARNING error occurs. If this E_USER_WARNING, we'll use our custom error handler and end the script:

<?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);
 }
 ?> 

The output of the above code looks like this:

Error: [512] Value must be 1 or below
Ending Script

Now that we've learned how to create your own errors and how to trigger them, let's look at error records.


Error record

By default, PHP sends error records to the server's .ini system or file, depending on the configuration of the error_log in php. By using error_log() function, you can send error records to a specified file or remote destination.

Sending yourself an error message via e-mail is a good way to get notification of a specified error.

Send an error message via E-Mail

In the following example, if a particular error occurs, we send an email with an error message and 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,
 "[email protected]","From: [email protected]");
 }

 //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);
 }
 ?> 

The output of the above code looks like this:

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

The messages received from the above code are as follows:

Error: [512] Value must be 1 or below

This method is not suitable for all errors. General errors should be logged on the server by using the default PHP recording system.

Learned how PHP handles errors, and then you'll learn in a new section how PHP can be resolved if an exception occurs.