Redirecting to an Error page when a Fatal Error occurs

Permanent Link: Redirecting to an Error page when a Fatal Error occurs 7. April 2009 Comment No Comment

Everyone surely has already encountered it: A fatal error on a page that is online including the white page you get to see because of it. There's a nice and easy way of showing an error page instead of a white page if a Fatal Error occurs by using output buffering. According to its documentation, ob_start() supports a callback as first parameter. The cool thing is that this callback is also called in case of a Fatal Error!

Here's how it works:

class Redirector
{
public static function redirectOnError($buffer)
{
$lastError = error_get_last();
if(!is_null($lastError) && $lastError['type'] === E_ERROR) {
header('HTTP/1.1 302 Moved Temporarily');
header('Status: 302 Moved Temporarily');
header('Location: error.php');
exit();
}
return $buffer;
}
}

ob_start(array('Redirector', 'redirectOnError'));
print('Hello');

foobar();

ob_end_flush();

The callback is called in the moment the content is flushed, that's why the flush should always be the last line in your output script if you wanna catch all Fatal errors. Since the callback is always executed, I added a check whether a fatal error occured, since we don't want a redirect when no error occurs. Also keep in mind that the callback has to return the buffered output (that is already passed to the callback as a parameter) which will be printed after its execution. (Note that error_get_last() is PHP >= 5.2.0)

Note: Instead of an 302 redirect, which I used in the example, you could also just output an error message on the same page:

public static function redirectOnError($buffer)
{
$lastError = error_get_last();
if(!is_null($lastError) && $lastError['type'] === E_ERROR) {
header('HTTP/1.1 503 Service Temporarily Unavailable');
header('Status: 503 Service Temporarily Unavailable');
$buffer = 'Sorry, an error occured';
}
return $buffer;
}

Thanks to Jakob and Lars for some input and refinements on this blogpost.

German book recommendation: "Das Zend Framework"

Permanent Link: German book recommendation: 4. April 2009 Comment No Comment

In case you're planning to work or already do work with the Zend Framework, there's a really good (german) book that just got out, which i test-read: Das Zend Framework: Von den Grundlagen bis zur fertigen Anwendung by Ralf Eggert.

Although this book is primarily for Zend Framework beginners, there is also a lot of content you may still not know even though you already work with ZF a bit longer. The code examples are really good and helpful and you really get to know a lot about ZF. The book shows how to build a web application step by step using ZF.

You can order the book at Amazon.