From the land of “why the hell didn’t I think of this sooner”… The following is a drop dead simple method to handling all HTTP error (403, 404, 500 etc.) pages with one single PHP file and a few tweaks to your htaccess.
.htaccess Code
The first step is to create/modify your .htaccess file. The following lines will tell the browser to redirect to the named page (errors.php) when any of the error codes listed are returned to the browser.
[sourcecode language=”plain”] ErrorDocument 400 /errors.phpErrorDocument 403 /errors.php
ErrorDocument 404 /errors.php
ErrorDocument 405 /errors.php
ErrorDocument 408 /errors.php
ErrorDocument 500 /errors.php
ErrorDocument 502 /errors.php
ErrorDocument 504 /errors.php[/sourcecode]
The PHP
The second step is to create a file called “errors.php” in your root directory. Add the following array and save the document.
[php]</pre>$status = $_SERVER[‘REDIRECT_STATUS’];
$codes = array(
400 => array(‘400 Bad Request’, ‘The request cannot be fulfilled due to bad syntax.’),
403 => array(‘403 Forbidden’, ‘The server has refused to fulfil your request.’),
404 => array(‘404 Not Found’, ‘The page you requested was not found on this server.’),
405 => array(‘405 Method Not Allowed’, ‘The method specified in the request is not allowed for the specified resource.’),
408 => array(‘408 Request Timeout’, ‘Your browser failed to send a request in the time allowed by the server.’),
500 => array(‘500 Internal Server Error’, ‘The request was unsuccessful due to an unexpected condition encountered by the server.’),
502 => array(‘502 Bad Gateway’, ‘The server received an invalid response while trying to carry out the request.’),
504 => array(‘504 Gateway Timeout’, ‘The upstream server failed to send a request in the time allowed by the server.’),
);
$title = $codes[$status][0];
$message = $codes[$status][1];
if ($title == false || strlen($status) != 3) {
$message = ‘Please supply a valid HTTP status code.’;
}
echo ‘<h1>Hold up! ‘.$title.’ detected</h1>
<p>’.$message.'</p>’;
<span style="font-family: Consolas, Monaco, monospace; font-size: 12px; line-height: 18px;">[/php]
Tweak and Enjoy
Adjust the text in the arrays to suit your needs and test it out. Super Simple!
Via PaperMashup