PHP Error Handling

by Vincy. Last modified on July 9th, 2022.

Error handling is an important feature to make efficient coding. PHP includes built-in error handling function to be invoked once an error occurred.

In this tutorial, we are going to cover possible ways of error handling techniques and corresponding functions in PHP. These are,

  • Error logging
  • Custom error handling
  • Triggering user generated errors
  • Error reporting

Simple Error Handling in PHP

PHP die() statement is very simple to handle errors. It stops program execution once an error occurred and displays error message sent as its parameter. For example,

<?php
if (isset($_POST["numerator"], $_POST["denominator"])) {
    $numerator = $_POST["numerator"];
    $denominator = $_POST["denominator"];
    if ($denominator != 0) {
        $quotient = $numerator / $denominator;
    } else {
        die("<strong>Error:</strong> Denominator should not be 0.");
    }
}
?>
<form name="frmDivision" method="post" action="">
	<input type="text" name="numerator" placeholder="numerator" value="" />
	<input type="text" name="denominator" placeholder="denominator" /> <input
		type="submit" name="devide" value="Devide" />
<?php if(isset($quotient)) {?>
<div>Result: <?php echo $quotient; ?></div>
<?php } ?>
</form>

In this example, it checks denominator’s value whether it is not equal to 0. If so, then execution will be continued with the division expression. Or else it will be stopped using die(). And the error message is,

Error:Denominator should not be 0.

If the denominator is 0 then division without die() statement will cause PHP warning,

default_error_handling

But simply stopping program execution is a minimal way while dealing PHP errors. So, we can go with other PHP error handling functions.

PHP Error Logging

Error logging writes errors into a placeholder for future references. It will be a file, an email address or any remote location.

Configuring Error Log using php.ini

In  .php.ini file we need to search for the error_log directive. This will contain log file path or any special keywords denoting system or web server logger. For example,

;error_log=<log-file-path> 
;error_log = syslog
;error_log = ""

if error_log=syslog, the errors are logged into System Logger. If no values are specified then it will search for server specification. For example, for apache, the error logging destinations are set with,

  • httpd.conf file’s ErrorLog directive.
  • httpd-vhosts.conf configuration’s <VirtualHost> container.

PHP error_log() Function

Using this function, we can use file path or an email address as error logging destination. The syntax of this function is

error_log($message, $message_type, $destination, $extra_headers)
  1. $message – Error message.
  2. $message_type – Integer ranges 0-4. Error Logging destination is based on this parameter.
  3. $destination – It might be the File name or email.
  4. $extra_headers – This parameter will be used if we are sending error log to an email (where $message_type = 1).

PHP error_log() Example

If we replace die() statement of the above code by the following code,

$message = "Error: Denominator should not be 0.";
error_log($message,0);

Then, the error message will be written into PHP log file. For example,

[28-Jan-2014 09:59:01 Europe/Berlin] Error: Denominator should not be 0.

Custom Error Handling

During program execution, once an error occurred, PHP calls its default error handler. We can also use custom functions to handle an error in our own way. We should set some information with this custom handlers. That information are,

  • Error message
  • Error levels representing type of the error
  • File in which the error occur
  • Line number in which the error occur
  • Error context

Error Handling using Custom Function

In this example, we have a custom error handler custom_handler(). This handler is invoked once an error occurred. It will print the error message with other details like filename and line number.

After defining the custom function we need to set it as a default error handling function using set_error_handler().

<?php

// Creating Custom Error Handler
function custom_handler($errorLevel, $errMessage, $errFile, $errLine, $errContext)
{
    echo "<b>Error [Level " . $errorLevel . "]: </b>" . $errMessage . " in <b>" . $errLine . "</b> in <b>" . $errFile . "</b><br/><br/>";
}
// Setting Custom Error Handler as Default
set_error_handler("custom_handler");
// Invoking Custom Error Handler
$colors = "Red";
foreach ($colors as $k => $v) {
    echo $colors[$k] . "<br/>";
}
?>

In this example, a string variable $colors are supplied to the foreach loop that will cause an error. Then, it will invoke our custom function and prints the error message,

custom_error_handler

PHP custom handler can handle the error types like E_ALL, E_WARNING, E_NOTICE, and more. At the same time some of the PHP errors like E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING and etc. cannot be handled by custom error handlers

Trigger Error using PHP

PHP allows to trigger user generated errors using trigger_error() function. For example, if we want to generate error message while getting an invalid email from a user, we can use this function.

PHP trigger_error() Example

<?php
if (isset($_POST["email"])) {
    // Triggering Error Handler Explicitely
    if (filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
        $message = "Valid Email Address";
    } else {
        trigger_error("Invalid Email");
    }
}
?>
<form name="frmDivision" method="post" action="">
	<input type="text" name="email" placeholder="email" value="" /> <input
		type="submit" name="submit" value="Validate" />
<?php if(isset($message)) {?>
<div>
		Validation Result: <b><?php echo $message; ?></b>
	</div>
<?php } ?>
</form>

If we submit invalid email address via this form, then trigger_error() will call PHP default error handler. The error message will be,

Notice: Invalid Email in ...\php_trigger_error.php on line ...

PHP Error Reporting

While handling errors in PHP, we can say which errors should be reported via browser or log. We have done this via both error_reporting configuration directive or through error_reporting() function.

Both of these options require error levels represented by PHP error constants. We can use a combination of more than one error constants separated by bitwise logical operators. For example,

error_reporting=E_ALL | E_STRICT & ~E_DEPRECATED
//OR
error_reporting(E_ALL | E_STRICT & ~E_DEPRECATED);

This setting allows PHP to let show all errors and coding standard warnings except deprecated errors.

Download PHP Error_Handling Source Code

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page