0

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
  • Since you have a classifieds website, I would assume you mean, for example, www.mysite.com/cars.php?id=5 where if the car with id=5 is not present you get redirected to a "item not found" type page? You're not talking about PHP's errors/warnings/notices right? Commented May 17, 2010 at 14:27
  • I you redirect the user to a generic error-page, you can't show specific error-messages anymore. Showing a generic error-page isn't a good idea. Commented May 17, 2010 at 14:28

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.