How to redirect and save error message on error?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
PhpMachine
Forum Commoner
Posts: 42
Joined: Thu Apr 19, 2007 11:26 am

How to redirect and save error message on error?

Post by PhpMachine »

Hi

When an error occures on a page (php- and mysql errors (or any error)), I want to save the error message
to a database.

Right now I have an "or die(mysql_error())" after each mysql_query() call. This displays the error directly to the user.
I'm using this when developing the website (having "display_errors = On" in php.ini).

If I now distribute the website and set "display_errors = Off", then no errors should be displayed to the
user, right?

The thing is, I want all errors to be displayed when developing, but when the website is up and running
public I want to switch off all errors and instead redirect to a 404-page where I save the error message
to a database.

Is this easily done?

Greeting
User avatar
aaronhall
DevNet Resident
Posts: 1040
Joined: Tue Aug 13, 2002 5:10 pm
Location: Back in Phoenix, missing the microbrews
Contact:

Post by aaronhall »

set_error_handler() is your best bet, though keep in mind that it completely bypasses build-in error handling. You can use your callback function to log the error and forward the user to a different page.
PhpMachine
Forum Commoner
Posts: 42
Joined: Thu Apr 19, 2007 11:26 am

Post by PhpMachine »

Hi aaronhall

I tried to use set_error_handler, but I still get a blank page with the mysql-error (die(mysql_error()).
I have set

Code: Select all

error_reporting  =  E_ALL
display_errors = Off
And at the beginning of my PHP-file, I have:

Code: Select all

set_error_handler('myErrorHandler');
function myErrorHandler($errno, $errstr, $errfile, $errline) {
 echo "error";
}
What am I doing wrong?
User avatar
aaronhall
DevNet Resident
Posts: 1040
Joined: Tue Aug 13, 2002 5:10 pm
Location: Back in Phoenix, missing the microbrews
Contact:

Post by aaronhall »

It's because die() isn't calling your error handler -- it will only execute the commands in the parentheses and "kill" the script. Since an invalid query won't throw a PHP error, you'd have to call trigger_error() inside the die() construct.
PhpMachine
Forum Commoner
Posts: 42
Joined: Thu Apr 19, 2007 11:26 am

Post by PhpMachine »

Thanks aaronhall!

It works perfectly.
Post Reply