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.
1. 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.
ini_set('display_errors', 1);
- 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:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
// PHP script code
?>
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.
2. 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.
3. 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:
<?php
// if you don't want PHP to report if it couldn't include a file
@include('script_name.php');
// if you don't want to see a 'division by zero' error
$num = @($x/$y);
?>
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.
error_log('Error message', 3, 'file_name.log');
- The number 3 dictates that the 'Error messages' will be write to a text file.
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:
<?php
if (isset($_POST['field_name'])) {
$var_name = $_POST['field_name'];
// Other PHP instructions
}
else {
echo "No data received from the 'field_name' field.";
}
?>
- 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 fallowing method:
<?php
$var_name = $_POST['field_name'];
// PHP instructions
?>
- 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 5
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.
<?php
$file = 'file_name.txt';
if (file_exists($file)) {
$file = fopen($file, 'r');
// ...
}
else echo 'File not found';
?>
- 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".
<?php
if (!isset($_GET['id'])) exit('Problem with $_GET variable');
?>
4. 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.
-
Syntax:
if(error occurs) {
trigger_error('Notice message');
}
- This produces an "Notice error".
In the next example an error occurs if the $_POST['name'] isn't defined.
<?php
if (!isset($_POST['name'])) {
trigger_error('You must add a name');
}
?>
- The output should be something like this:
Notice: You must add a name in C:\server\www\file_name.php on line 5
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().
-
Syntax:
if(error occurs) {
throw new Exception('Notice message');
}
- This reports a "Fatal error".
In the next example a Fatal error occurs if the $_GET['id'] isn't defined.
<?php
if (!isset($_GET['id'])) {
throw new Exception('The ID is missing.');
}
?>
- 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.