Error handling in PHP

Error handling in PHP

Online by JSC0d3
June 27, 2014 | | 1346 recognitions

PHP is the most popular server-side web programming language today, so it’s important to know how to resolve any errors that may occur when your PHP code is executed. In this article, we will look at the basics of how to do error handling in PHP, using the built-in functions, writing custom error handler functions, and with Exception error handling.

Errors are the most common event a developer faces when programming. Errors can be categorized as syntactical, run-time, or logical: missing the semicolon at the end of a statement is an example of a syntax error; trying to connect to a database when the server is down is an example of a run-time error; providing incorrect data to a variable is an example of a logic error.

Error handling in PHP

To help reduce the number of errors in your code, and to mitigate their effects, proper error handling is essential in your web application.

PHP Error Reporting Levels

All errors and warnings should be logged. Based on the severity of an error, notifications should be sent out to other systems/teams. So that you can better gauge its severity, PHP provides several built-in error levels to describe the nature of an error. Each level is represented by an integer value and named constant which can be used by the programmer. The table below is taken from the official PHP documentation and shows some of the different levels.

Show Errors and Error Handling
Error handling in PHP

The levels can be masked together with bit-operators to include or subtract them from PHP’s configuration. For example, E_ALL|E_STRICT enables all errors and warnings with the addition of E_STRICT (necessary in versions of PHP prior to 5.4).

PHP provides a few configuration directives related to logging and displaying errors. Their values are generally different depending on whether the system is in a development or a production environment. This table shows some of the error-related directives.

The configuration directives can be set either in php.ini, in a web server configuration file (httpd.conf or .htaccess file), or at run-time in your script using the ini_set() function. Read the documentation for more information on the directives and how/where to set them.

Creating Custom Error Handlers

It’s also good practice not to display raw errors to the end user. Errors that are displayed should be abstracted with friendly, custom error messages. PHP not only provides built-in functions for logging and displaying errors, but also for raising them. You can pragmatically trigger an error of a specific level using trigger_error(). For example, this code triggers an E_USER_NOTICE warning if the value of $test is greater than 1:

$test = 5;
if ($test > 1) {
    trigger_error('Value of $test must be 1 or less', E_USER_NOTICE);

Triggering errors with trigger_error() is useful when you have an error-handling infrastructure in place, allowing you to unify the handling of both custom errors and the errors and warnings raised by PHP.

If you want to implement customized error handling strategies like sending an email or logging errors to a database based on their severity, then you’ll need to define custom error handlers using set_error_handler(). The function accepts two arguments: a callback function or static method that will be invoked when the error is raised, and optionally the error level the function/method handles. The signature of the callback is:

handler(int $errno, string $errstr, string $errfile, int $errline, array $errcontext)
  • $errno — specifies the error reporting level for the error (required)
  • $errstr — specifies the error message (required)
  • $errfile — specifies the name of the file in which the error occurred (optional)
  • $errline — specifies the line number in which the error occurred (optional)
  • $errcontext — specifies an array containig every variable in the scope the error occurred (optional)

Let’s take a look at a custom error handler function.

function errorHandler($errno, $errstr, $errfile, $errline) {
    static $db;
    if (empty($db)) {
        $db = new PDO(DSN, DBUSER, DBPASS);
    $query = "INSERT INTO errorlog (severity, message, filename, lineno, time) VALUES (?, ?, ?, ?, NOW())";
    $stmt = $db->prepare($query);
    switch ($errno) {
        case E_NOTICE:
        case E_USER_NOTICE:
        case E_DEPRECATED:
        case E_USER_DEPRECATED:
        case E_STRICT:
            $stmt->execute(array("NOTICE", $errstr, $errfile, $errline));
        case E_WARNING:
        case E_USER_WARNING:
            $stmt->execute(array("WARNING", $errstr, $errfile, $errline));
        case E_ERROR:
        case E_USER_ERROR:
            $stmt->execute(array("FATAL", $errstr, $errfile, $errline));
            exit("FATAL error $errstr at $errfile:$errline");
            exit("Unknown error at $errfile:$errline");
$test = 5;
if ($test > 1) {
   trigger_error("Value of $test must be 1 or less", E_USER_NOTICE);

The above snippet registers an error handler that does the following: when non-fatal errors occur, a record will be inserted into database instead of displaying the error and logging it to a file; When a fatal error occurs, it will be logged in database and terminate your script.

There are some limitations to custom error handlers you should be aware of, however. The error handler bypasses PHP’s standard error handling behavior, so it can’t handle errors that may arise within your handler itself. In the event the database server is down, for example, the above function would fail to record the log. Also, the error handler is not able to catch certain internal errors, like E_CORE_ERROR and E_COMPILE_ERROR, or E_STRICT errors in the same file the handler is defined in since those errors occur before the handler has a chance to be registered.

Handling Errors using Exceptions

However good of an error handling framework you have in place, there will always be problems at run-time. Of course you don’t want these errors to show up in the user’s browser. This is where exception handling enters the picture. Exceptions allows you to handle errors and exceptional situations gracefully.

Exceptions are represented in PHP by the class Exception (or any of its subclasses). They can be raised using throw and can be caught using a try/catch block. You can extend Exception to create custom exception types for trapping specific errors.

The code that may trigger an exception is placed within the try block, and the code to handle the exception is placed within the catch block. Consider the following snippet:

try {
   $data = $this->getDataFromService();
catch (Exception $e) {
   echo "Caught exception: " . $e->getMessage() . "n";

If an exception is thrown by the fictitious getDataFromService() method, it will be caught in the catch block and a message will be displayed. If getDataFromService() executes successfully then the flow will pass over the catch block and continue through the rest of the script. Any exceptions that are thrown and not caught will generate an E_FATAL error with the message “Uncaught Exception”.

The Exception class offers six different methods to access information about what caused the problem.

  • getMessage()- message of exception
  • getCode() – code of exception
  • getFile() – source filename
  • getLine() – source line
  • getTrace() – n array of the backtrace()
  • getTraceAsString() – formated string of trace

Creating a Custom Exception Handler

PHP will let you throw any object as if it were an exception, but as a rule of thumb the exception should extend PHP’s built-in Exception class. Based on the object’s type, you can handle the exceptions differently. Custom exception handling can perform suitable actions like logging error messages in file, providing exact details about the line on which the error occurred by examining the calling stack.

class NameException extends Exception { }
class EmailException extends Exception { }
$name = "";
$email= "";
try {
   if (empty($name)) {
       throw new NameException();
   elseif (empty($email)) {
       throw new EmailException();
   else {
       echo "Name is " . $name . "<br>";
       echo "Email is " . $email;
catch (NameException $n) {
   echo "A name was not provided.";
catch (EmailException $e) {
   echo "An email address was not provided.";

Re-throwing Exceptions

try/catch blocks can be nested. Sometimes you’ll want to catch an exception, look at some of its properties, and then throw it again to let a parent catch block handle it. This can often be useful to check an error condition and decide whether it should be fatal or not. This example code demonstrates re-throwing an exception:

class FileExistException extends Exception { }
class FileReadException extends Exception { }
$filename = 'D:Exception.txt';
try {
    try {
        $text = file_get_contents($filename);
        if ($text === false) {
            throw new Exception();
    catch (Exception $e) {
        if (!file_exists($filename)) {
            throw new FileExistException($filename . " does not exist.");
        elseif (!is_readable($filename)) {
            throw new FileReadException($filename . " is not readable.");
        else {
            throw new Exception("Unknown error accessing file.");
catch (FileExistException $fe) {
    echo $fe->getMessage();
catch (FileReadException $fr) {
    echo $fr->getMessage();

Uncaught Exception Handler

Similar to how set_error_handler() allows you specify a function to handle run-time errors, the set_exception_handler() function allows you to handle exceptions that make it all the way up the call stack without being caught by any catch blocks. For example, if an exception makes it all the way up your stack, it would be a good idea to log it in a log file. You can create a callback function and register it with set_exception_handler().

set_exception_handler(function ($exception) {
   $file = "var/log/exceptionLog.log";
   file_put_contents($file, $exception->__toString(), FILE_APPEND);
throw new Exception();
JSC0d3's Logo
About JSC0d3

JSC0d3 is an entrepreneur, online marketer, and an employee of an IT company. When not building websites, creating content, or helping customers improve their online business, spend time with their wife and two beautiful children. Although he still feels new in WordPress, he enjoys sharing what he has learned with all of you! If you want to get in touch with him, you can do this through this website.

On the same idea

Posted by | February 9, 2019

WordPress' wp_link_pages() function, used for displaying page links in multi-page posts, lacks one big feature You can display a list of...

Posted by | December 14, 2018

Preliminary step: Testing whether the code complies with the format of a fiscal identification code (CIF) That is, the maximum length should be 10...

Posted by | November 8, 2017

Nowadays, a lot of bloggers choose to remove HTML tag from WordPress websites However, for beginners and newbies in this field, they may feel...

Previous PostBackNext Post

Leave here an impression