jump to navigation

A Basic Introduction Into PHP Error-Handling November 10, 2011

Posted by Tournas Dimitrios in PHP.

This article is just a basic introduction in PHP error handling . My primary audience for this article is the novice PHP user – if you’re an advanced user , you probably already know enough and might prefer to skip this article . Everyone else – keep reading ! You’ll learn about PHP’s built-in error reporting levels , and how to handle errors with custom error handlers and exception handling .

For a developer error handling is probably the most important concept , no matter what programming language he has to deal with . PHP has sixteen separate levels to describe the nature of an error and offers several “tools” for handling these errors , like : configuration directives (determines the reporting sensitivity level ) , temporarily error-suppresing (@-symbol) , error-logging , custom error-handling and finaly exceptions . Let’s explore these five tools by practical examples .

Errors can be categorized as :

  • syntactical : missing the semicolon at the end of a statement is an example of a syntax error
  • run-time : trying to connect to a database when the server is down is an example of a run-time error
  • logical : providing incorrect data to a variable is an example of a logic error . To help reduce the number of errors in your code , and to mitigate their effects , proper error handling is essential in your web application .

Temporarily error-suppresing :

PHP offers one error control operator , the at symbol @ , prefixing a command with this operator will suppress any error that could be produced by this command . I recommend using the @ once your website is in production , displaying error-messages to your visitors is messy and potentially a security issue . I generally don’t use the @ on development servers because I want to be aware of errors during development . For example :

  • trying to reference a nonexistent file with include_once(‘filename.ini’) would cause an error .
    @include_once ‘ somefile.php’ ;
  • trying to connect to a database
    $conn = @mysql_connect(“localhost”, “root”, “root123”);

Error-logging :

Logging data to a file in PHP can be as simple or as complex as you want to make it . Let’s use a buld-in PHP file-manipulation function file_put_contents . A good practice is to encapsulate the logic into a function with a timestamp and then use it within your code as and when required :

function customlog($filename, $msg) {

$msg = "[" . date("Y/m/d h:i:s", mktime()) . "] " . $msg."\n";
file_put_contents($filename, $msg , FILE_APPEND);
$val = "This is a string message" ;
if (!is_numeric($val)) { customlog("myCustom.log", "An error was encountered"); }
$a = array("dog", "cat", "monkey");
if (!in_array('apple', $a)) { customlog("myCustom.log", "No fruit available"); }
$conn&nbsp;= @mysql_connect("localhost", "root", "root123");
if (!$conn)
customlog("myCustom.log", "Could not connect to database");
die("Could not connect to database");


Error handling using exceptions :

PHP 5 has an exception model similar to that of other programming languages . An exception can be thrown , and caught (“catched”) within PHP. This catched exception-object has methods that can be called . These methods make it easier for a try-catch function to react to exceptions . For example , the getMessage() function will let you get an exception’s error message , which you can then log or show on the browser .Each try must have at least one corresponding catch block . Multiple catch blocks can be used to catch different classes of exceptions . A basic example could be :

try {
$error = 'Throw this error';
throw new Exception($error);
echo 'Never get here';
catch (Exception $e)
&nbsp; echo 'Exception caught: ', $e->getMessage(), "\n";

Creating Custom Error Handlers :

It is a fairly common task to bring up an error message similar to PHP’s when your code is being used incorrectly , and this is what trigger_error() does . While it is not often necessary to throw up error messages in your code when only you use it , it becomes much more important when your code is being distributed to other developers . The trigger_error() function takes two parameters :

  • The first parameter can be whatever you wish (a custom message )
  • The second parameter however , affects how the script should react to the error . If you do not provide the second parameter , the default is a user notice – a minor message that many people might not even see . You can select from any of the user error types as the second parameter , which can allow you to halt execution of the script if your error is triggered .

The following code snippet will record an error-message into a Mysql table . An if-statement evaluates a value and may triger an custom function which will record a message into a Mysql table . That’s just an example , we can adapt the code and build custom functionality .

function recordError($errno, $errstr, $errfile, $errline) {

$mysqli = new mysqli("localhost", "root", "", "test"); 

switch ($errno) {
case E_NOTICE:
case E_STRICT:
$mysqli->query("INSERT INTO errorlog (errorlevel, message, filename, lineno, time) VALUES ( 'NOTICE', \"$errstr\", \"$errfile\", $errline ,NOW())");
echo "$errstr ";


$mysqli->query("INSERT INTO errorlog (errorlevel, message, filename, lineno, time) VALUES ( 'WARNING', \"$errstr\", \"$errfile\", $errline ,NOW())");

case E_ERROR:

$mysqli->query("INSERT INTO errorlog (errorlevel, message, filename, lineno, time) VALUES ( 'FATAL', \"$errstr\", \"$errfile\", $errline ,NOW())");
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);


Configuration directives :

PHP provides a few configuration directives related to displaying errors . Their values are generally different depending on whether the system is in a development or a production environment . These configuration directives can be set either in php.ini (web server’s configuration file ) or as directives into .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 . A couple important error-related directives are :

  • error_reporting : Sets the error reporting level . During the development stage , you’ll likely want all errors to be reported . Therefore , consider setting the directive like this :
    error_reporting = E_ALL & E_STRICT
  • display_errors : Sets wether errors should be printed on the screen as part of the output .

This article made just an introduction to basic PHP error handling concepts . Each section deserves a whole separate article .



No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s