Error Handling in PHP

When creating scripts and web applications, error handling is an important part. If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks.

Here, We will show different error handling methods.

  • Simple "die()" statements
  • Custom errors and error triggers
  • Error reporting

Basic Error Handling: Using the die() function

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

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

If the file does not exist you might get an error like 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 the user from getting an error message like the one above, we test whether the file exist before we try to access it.

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

Now if the file does not exist you get an error like this:

File not found

The code above is more efficient than the earlier code, because it uses a simple error handling mechanism to stop the script after the error.

However, simply stopping the script is not always the right way to go. Let's take a look at alternative PHP functions for handling errors.


Creating a Custom Error Handler

Creating a custom error handler is quite simple. We simply create a special function that can be called when an error occurs in PHP.

This function must be able to handle a minimum of two parameters (error level and error message) but can accept up to five parameters (optionally: file, linenumber, and the error context).

Syntax:

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

Parameter:

  • error_level: Required. Specifies the error report level for the user-defined error. Must be a value number. See table below for possible error report levels.
  • error_message: Required. Specifies the error message for the user-defined error.
  • error_file: Optional. Specifies the filename in which the error occurred.
  • error_line: Optional. Specifies the line number in which the error occurred.
  • error_context: Optional. Specifies an array containing every variable, and their values, in use when the error occurred.

Error Report Levels

These error report levels are the different types of error the user-defined error handler can be used for.

ValueConstantDescription
2E_WARNINGNon-fatal run-time errors. Execution of the script is not halted
8E_NOTICERun-time notices. The script found something that might be an error, but could also happen when running a script normally
256E_USER_ERRORFatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error()
512E_USER_WARNINGNon-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error()
1024E_USER_NOTICEUser-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error()
4096E_RECOVERABLE_ERRORCatchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler())
8191E_ALLAll errors and warnings (E_STRICT became a part of E_ALL in PHP 5.4)

Now lets create a function to handle errors.

<?php
	function customError($errno, $errstr) {
		echo "<b>Error:</b> [$errno] $errstr<br>";
		echo "Ending Script";
		die();
	}
?>

The code above is a simple error handling function. When it is triggered, it gets the error level and an error message. It then outputs the error level and message and terminates the script.

Now that we have created an error handling function we need to decide when it should be triggered.


Set Error Handler

The default error handler for PHP is the built in error handler. We are going to make the function above the default error handler for the duration of the script.

It is possible to change the error handler to apply for only some errors, that way the script can handle different errors in different ways. However, in this example we are going to use our 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.


Trigger an Error

In a script where users can input data it is useful to trigger errors when an illegal input occurs. In PHP, this is done by the trigger_error() function.

Example:

In this example an error occurs if the "test" variable is bigger than “1”.

<?php
	$test=2;
	if ($test>=1) {
		trigger_error("Value must be 1 or below");
	}
?>

The output of the code above should be something like this.

Notice: Value must be 1 or below
in C:\webfolder\test.php on line 6

An error can be triggered anywhere you wish in a script, and by adding a second parameter, you can specify what error level is triggered. Possible error types.

  • E_USER_ERROR - Fatal user-generated run-time error. Errors that can not be recovered from. Execution of the script is halted.
  • E_USER_WARNING - Non-fatal user-generated run-time warning. Execution of the script is not halted.
  • E_USER_NOTICE - Default. User-generated run-time notice. The script found something that might be an error, but could also happen when running a script normally.

Example:

In this example an E_USER_WARNING occurs if the "test" variable is bigger than "1". If an E_USER_WARNING occurs we will 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 code above should be something like this.

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

Now that we have learned to create our own errors and how to trigger them, lets take a look at error logging.


What is an Exception?

With PHP 5 came a new object oriented way of dealing with errors. Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception.

This is what normally happens when an exception is triggered.

  • The current code state is saved.
  • The code execution will switch to a predefined (custom) exception handler function.
  • Depending on the situation, the handler may then resume the execution from the saved code state, terminate the script execution or continue the script from a different location in the code.

We will show different error handling methods.

  • Basic use of Exceptions.
  • Creating a custom exception handler.
  • Multiple exceptions.
  • Re-throwing an exception.
  • Setting a top level exception handle.

Note: Exceptions should only be used with error conditions, and should not be used to jump to another place in the code at a specified point.


Basic Use of Exceptions

When an exception is thrown, the code following it will not be executed, and PHP will try to find the matching "catch" block. If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message.

Lets try to throw an exception without catching it.

<?php
	//create function with an exception
	function checkNum($number) {
		if($number>1) {
			throw new Exception("Value must be 1 or below");
		}
		return true;
	}
	//trigger exception
	checkNum(2);
?>

The code above will get an error like this.

Fatal error: Uncaught exception 'Exception'
with message 'Value must be 1 or below' in C:\webfolder\test.php:6
Stack trace: #0 C:\webfolder\test.php(12):
checkNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6

Try, Throw and Catch

To avoid the error from the example above, we need to create the proper code to handle an exception. Proper exception code should include.

try - A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown"

throw - This is how you trigger an exception. Each "throw" must have at least one “catch”.

catch - A "catch" block retrieves an exception and creates an object containing the exception information.

Lets try to trigger an exception with valid code.

<?php
	//create function with an exception
	function checkNum($number) {
		if($number>1) {
		throw new Exception("Value must be 1 or below");
		}
		return true;
	}
	//trigger exception in a "try" block
	try {
		checkNum(2);
		//If the exception is thrown, this text will not be shown
		echo 'If you see this, the number is 1 or below';
	}
	//catch exception
		catch(Exception $e) {
		echo 'Message: ' .$e->getMessage();
	}
?>

The code above will get an error like this.

Message: Value must be 1 or below

Example Explained:

The code above throws an exception and catches it.

  • The checkNum() function is created. It checks if a number is greater than 1. If it is, an exception is thrown.
  • The checkNum() function is called in a "try" block.
  • The exception within the checkNum() function is thrown.
  • The "catch" block retrieves the exception and creates an object ($e) containing the exception information.
  • The error message from the exception is echoed by calling $e- >getMessage() from the exception object.

However, one way to get around the "every throw must have a catch" rule is to set a top level exception handler to handle errors that slip through.