How to handle those pesky errors in PHP(Page 1 out of 4)
Let's face it - none of us write perfect code, and your almost-perfect PHP scripts are bound to throw an error now and then, even if you've tested them hundreds of times. It's simply impossible to rule out everything, and that's no problem really, as long as you handle the errors properly.
PHP scripts should never publicly display any error on a live production website, as it could lead to security problems, and it just looks bad to your visitors. Can you imagine your bank's website throwing an error when trying to view your bank account? I'm sure that wouldn't inspire much faith in you.
That's why in this article I'm going to show you how to handle errors in PHP. In this article I will first take you through the basics of error handling, by catching all PHP errors with the set_error_handler() function. After that we'll have a look a new PHP 5 feature called Exceptions which can also be used to create and catch errors. At the end of the article I will show you how to trigger your own errors.
But before we begin with anything, let's have a look at how error reporting works in PHP.
Error reporting in PHP
Error reporting in PHP can be turned on and off in your php.ini file, and it's also possible to define what type of errors should be displayed. There are 11 error types in PHP (12 if you're using PHP5), and they can be found at http://nl2.php.net/manual/en/ref.errorfunc.php#errorlevels. Each level defines a different type of error, but it's usually recommended to use E_ALL on your developer environment, and E_ALL & ~E_NOTICE on your production environment.
In your php.ini several settings can be set related to error reporting. To completely turn off error reporting, you can set the display_errors setting to off, but this is only recommended on production servers, and your development server should always have errors on. It's also possible to turn on error logging, and have all the errors logged to a file.
For this article, make sure error reporting is turned on (display_errors = On) and that your error level is set to E_ALL (error_reporting = E_ALL).
It's also possible to set the error reporting level in your scripts, with the error_reporting() function, e.g.
// Report all PHP errors
That's pretty much the basics of errors in PHP. Let's move on to handling errors.