PHP Reporting and handling errors

Dec 03, 2008 Author: City Hall

When developing a PHP project, whether it’s a simple website or a much larger web application, it’s always a good idea to take into account the potential appearance of errors in your PHP code. An error occurs whenever PHP tries to execute an instruction which either results in an impossible outcome, or otherwise prevents the script from executing in the manner intended by the programmer.

Errors range from simple fatal errors, where program execution is halted at the point of the fault - usually a syntax error or a call to a function that doesn’t exist - to more complex errors where the cause of the problem isn’t immediately clear, and an indepth review of the code must be carried out to pinpoint the flaw.

Undefined Variables (and other little glitches)

Dealing with errors in a meaningful and graceful manner is a major consideration when developing PHP code. The default behaviour of PHP when encountering an error is to output a very simple line of text, with very basic formatting. It’s really quite ugly, and not the sort of thing you want your visitors to be seeing:

echo ($hello_world);

Here, we are trying to access a variable $hello_world which has not been defined. The resulting output will be a screen with the following text

Notice: Undefined variable: hello_world in C:\local\myphp.php on line 5

Note: You might not see this appear on screen right away. PHP sometimes is not fully set up to display all errors as they happen. To change PHP’s default behaviour, add the following lines before the echo statement above

1
2
error_reporting(E_ALL|E_STRICT);
ini_set("display_errors", TRUE);

Line 1 tells PHP to report all errors (including “strict” errors, which aren’t included as part of the E_ALL argument). Line 2 sets a PHP configuration variable which instructs PHP to always display errors. This value is also hidden away in the php.ini configuration file, but that’s not always accessible, so this way of setting it is perfectly valid.

One way to get around this error message cropping up in the first place is to make sure you’ve properly defined the variable before you use it. And if you’re uncertain whether or not the variable is defined, you can always place checks before calling it, like so

//the isset function checks if a given variable is defined or not
if(isset($hello_world){
echo $hello_world;
} else {
echo "The variable 'hello world' couldn't be located";
}

But that’s not terribly practical when you have to do the same checks for every variable, and the error message displayed still makes it all too clear to the visiting public that something’s gone wrong.

In the next section, we will look at ways of handling these error messages in a much more efficient manner

Continue to the next part of this Tutorial


views 5157
  1. Add New Comment