views:

57

answers:

3

My classifieds website uses mainly PHP and MySql.

On error, (for example if a variable isn't found), I would like to have an error-page to show, is this possible? And I mean for every error to point to the same error-page.

I am thinking about htaccess, but maybe there are other ways also?

Same with MySql, how is it done there?

Thanks

+2  A: 

You can do stuff with the PHP error handling methods that will probably be what you are looking for. There is a decent tutorial here.

jaltiere
+2  A: 

You can attach a custom error handler to do the redirect. First, enable output buffering, otherwise it is not possible to call the required header() function.

ob_start();

// This function will be our custom error handler
function redirect_on_error(int $errno , string $errstr) {
    // Ignore the error, just redirect the user to an error page
    ob_end_clean(); // Erase any output we might have had up to this point
    header('Location: error.html'); // Or wherever you want to redirect to
    exit;
}

set_error_handler('redirect_on_error'); // Set the error handler

// Your code goes here

ob_end_flush(); // End of the page, flush the output buffer
Rodin
+2  A: 

Personally, I use error exceptions all the time (http://us.php.net/manual/en/class.errorexception.php)...

So, at the beginning of my code, I have the following:

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");

Then, I wrap everyting in a giant try{}catch{} block. So I can "catch" the error higher, but if I don't, it displays an error message to the client:

ob_start();
try {
    //Do Stuff Here, include files, etc
} catch (Exception $e) {
    ob_end_clean();
    //Log the error here, including backtraces so you can debug later
    //Either render the error page here, or redirect to a generic error page
}

The beauty is that it'll catch ANY kind of error. So in my DB class, I simply throw a DatabaseException (which extends Exception). So I can try/catch for that when I make my call if I want to fail gracefully, or I can let it be handled by the top try{}catch block.

ircmaxell