Error Handling and Debugging

category: Basics
Created by: Dr.Ferrous

Error Handling and Debugging

category: Basics
Created by: Dr.Ferrous
twitter google+ facebook pinned 

When developing Web applications with PHP, many times you end up with PHP problems and the script don't works properly and returns an error. The default error handling in PHP is an error message with filename, line number and a message describing the error sent to the browser.

For example, the fallowing error message occurs when a semicolon is missing:

Parse error: syntax error, unexpected T_VARIABLE, expecting ',' or ';' in C:\server\www\file_name.php on line 8


Or, when is accessed a php file that not exist on the server, at that location.

Error 404

The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.

Error Report levels

PHP provides useful and descriptive error messages when things go awry. But it doesn't show all these errors when running using its default configuration. This makes sense to not let the users seeing PHP specific error messages, but it also makes everything that much more confusing for debugging the script.
To be able to see PHP's errors, you must turn on the display_errors.
To turn on display_errors in a script, use the ini_set() function.

Including this line in a script will turn on display_errors for that script.

ini_set() allows a script to temporarily redefine a parameter from the php.ini configuration file.

Once you have PHP set to display the errors that occur, you can adjust the level of error reporting using the error_reporting() function. This function is used to establish what type of errors PHP should report on.
The error_reporting() function takes either a number or a constant, using the values in the fallowing table:


Number Constant Description
1 E_ERROR Fatal run-time errors (that stop execution of the script). It's normally caused by referring to a nonexistent file or function.
2 E_WARNING Non-fatal run-time errors. This alerts you to a serious problem, such as a missing include file, but the execution of the script is not halted.
4 E_PARSE Parse errors. This means ther's a mistake in your code syntax, such as mismatched quotes or a missing semicolon or closing brace. It stops the script, and it does't allow any HTML output to be displayed.
8 E_NOTICE Advises you about relatively minor issues, such as the use of a nondeclared variable. This type of error wo't stop your page from displaying.
256 E_USER_ERROR Fatal user-generated error, generated by the trigger_error() function.
512 E_USER_WARNING Non-fatal user-generated warnings, generated by the trigger_error() function.
1024 E_USER_NOTICE User-generated notice, generated by the trigger_error() function.
2048 E_STRICT Warns recommendations for compatibility and interoperability
8191 E_ALL All errors, warnings, and recommendations


error_reporting(0) - turns error reporting off entirely (errors will still occur; you just won't see them anymore).
error_reporting(E_ALL) - will tell PHP to report on every error that occurs.
error_reporting(E_ALL & ~E_NOTICE) - reports all errors except for notifications.

For example, if you want the php script displays all errors, you can use:

It isn't wise to let PHP to report on any kind of error. For security and aesthetic purposes, it's generally unwise for users to see PHP's detailed error messages. Error messages dealing with the database will reveal certain behind-the-scenes aspects of your Web application. It's better to turn on "display_errors", and "error_reporting(E_ALL)" only during the development stages, or when you debug it.

Debugging errors

When it comes to debugging, you'll best learn from experience. Understanding the common causes will shorten the time it takes to fix errors. PHP errors fall into three general areas: Syntactical, Run time, Logical.

Syntactical errors are the most common and the easiest to fix. You'll see them if, for example, omit a semicolon. PHP will show an error, including the line PHP thinks it's on.

Parse error: syntax error, unexpected T_VARIABLE in C:\server\www\file_name.php on line 6

This type of error stops the execution of the php script. Also, SQL errors are normally a matter of syntax.

Run-time errors include those things that don't stop a PHP script from executing but do stop the script from doing everything it was supposed to do. This occurs when, for example, it is called a function using the wrong number or types of parameters.

Missing argument 1 for function_name(), called in C:\server\www\file_name.php on line 6 and defined in C:\server\www\file_name.php on line 5

Logical errors are actually the worst, because PHP won't necessarily report it to you. These are outand-out bugs: problems that aren't obvious and don't stop the execution of a script.

When you write a PHP program, keep the following things:

  • End every statement (but not language constructs like loops and conditionals) with a semicolon.
  • Each opening character: parentheses, curly braces, and square brackets, must be closed.
  • Single quotes can be closed only with single quotes and double quotes with double quotes.
  • Escape, using the backslash, all singleand double-quotation marks within strings, if the string is written between the same type of quotes.

These are some of the most common errors you'll see in PHP, along with their most probable causes:

Blank Page: HTML problem, or PHP error and display_errors or error_reporting is off.
Parse error: This means ther's a mistake in your code syntax, such as mismatched quotes or a missing semicolon or closing brace. It stops the script in its tracks, and it does't allow any HTML output to be displayed.
Empty variable value: Forgot the initial $, misspelled or miscapitalized the variable name, or inappropriate variable scope (with functions).
Undefined variable: Reference made to a variable before it is given a value or an empty variable value.
Call to undefined function: Misspelled function name, PHP is not configured to use that function, or document that contains the function definition was not included.
Cannot redeclare function: Two definitions of your own function exist; check within included files.
Headers already sent: White space or other character exists in the script before the PHP tags, data has already been printed, or a file has been included.

About syntactical errors, if the PHP error message says the error is occurring on line 8, that doesn't mean that the mistake is on that line. Often is at one or a few lines above.

If PHP reports an error on the last line of your document, this is probably because a mismatched parenthesis, curly brace, or quotation mark was not caught until that moment.

PHP Error Handling

If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks.

Individual errors can be suppressed in PHP using the @ operator.
The @ operator works only on expressions, like function calls or mathematical operations. You cannot use @ before conditionals, loops, function definitions, etc. For example:


By default, PHP sends an error log to the servers logging system or a file, depending on how the error_log configuration is set in the php.ini file. You can use the error_log() function to send error logs to a specified file or a remote destination.

When you work with external data type, like data received from forms or URL, or from external files, it's indicated to test if that data /variable exists, to avoid the error messges and also to understand easily where the problem is.
For example, if the php script uses data received from a HTML form field, we can use the fallowing construction:


If the script receives data (through post method) from the form field named 'field_name', executes the code within the braces of "if()" statement, otherwise is executed the code from "else" block and displays the message: No data received from the 'field_name' field.
The isset() function checks and returns TRUE if a variable exists (if is defined), otherwise returns FALSE.

But if you use the following method:


If the script not receives data from the form field named 'field_name', it result an error like this:

Notice: Undefined index: field_name in C:\server\www\script_name.php on line 2


If you work with data from external file, you can use the file_exists() to check if that file exists before using it. This function returns TRUE if a file (added as a parameter) exists, otherwise returns FALSE.

If the file from $file exists, the script runs the code with that file (from the block braces of if()), otherwise displays "File not found".

You can also pass exit() a string that will be printed out in the browser. This function terminates the execution of the script.
- Example, if the script don't receives data through GET method (with 'id' index), or the $_GET['id'] variable isn't defined, it will stop the execution of the next lines and displays "Problem with $_GET variable".

Trigger an Error

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

This produces an "Notice error".
In the following example an error occurs if the $_POST['name'] isn't defined.

The output should be something like this:

Notice: You must add a name in C:\server\www\file_name.php on line 5

Handling exceptions

When a problem arises, many built-in classes automatically throw an exception (or generate a special type of object that contains details of what caused the error and where it arose).
You can also throw custom exceptions, using throw new Exception().

This reports a "Fatal error".
In the following example a Fatal error occurs if the $_GET['id'] isn't defined.

The output should be something like this:

Fatal error: Uncaught exception 'Exception' with message 'The ID is missing.' in C:\server\www\file_name.php:6 Stack trace: #0 {main} thrown in C:\server\www\file_name.php on line 6


This method of handling errors is more used in class code.