Handling Errors

Handling errors in PHP is fairly straightforward. Most of the time a function will return 0 if it fails for one reason or another, so to catch this you can always use an if statement.

<?php
if(!someFunction($value))
{
    echo(“An error has occurred”);
    return;
}
?>

This allows you to do whatever you want when an error occurs. You could just let users know something has gone wrong, or you could even go as far as to take them to a detailed error page that allows them to e-mail the administrator with a notification of the error.

However, there are some functions that will generate an error if they fail. If this is the case you can suppress the error by using the at (@) symbol.

<?php
if(!@mysql_connect($db, $username, $password))
{
    echo(“An error has occurred while trying to open the database”);
    return;
}
?>

This will suppress the PHP error message but the function will still return 0, letting you know that it has failed. Be aware that if you suppress a fatal error no message will be displayed but processing of the script will halt dead in its tracks. So I recommend running your code without the suppression when testing to see where errors occur and adding the suppression in when you are finished debugging your code.

If you suppress error messages you can always retrieve the full error message through the $php_errormsg variable. This variable will always contain the last error that occurred in the PHP interpreter.

When writing this book I ran into an error that occurred when trying to write to a db file that I created and I had errors turned off. So every time I executed the script nothing would show up on the screen and no file was ever created. It took me a few minutes to realize what was going on. When I finally did, I got an error message that looked like Figure C.5.

I first thought to myself, “What the hell is that; it makes no sense at all.” Even though this error was quite cryptic, it gave me a direction. Since it was having a problem with the dba_open() line, I thought I must not have included the db extensions. When I checked the

Figure C.5. Error message.


php.ini file I discovered I had included the db extensions. Then, after several hours of searching the forums, I ran the phpinfo() function. When I did this I discovered that the version of PHP that I was running did not support the db2 format, but it did support the db3 format. Once I made this simple change everything worked perfectly. It just goes to show that using those errors may not lead you to an immediate fix but it will at least point you in the right direction.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset