Skip to content

Instantly share code, notes, and snippets.

@amgraham
Last active October 1, 2015 04:58
Show Gist options
  • Save amgraham/1925679 to your computer and use it in GitHub Desktop.
Save amgraham/1925679 to your computer and use it in GitHub Desktop.
A simple way to present error status codes in a web-based application
// error.php
/* $code would be set when included in another file, otherwise we assume apache is calling us, and look for $_GET["code"] */
$code = (empty($code)) ? $_GET["code"] : $code;
/* we messed something up, fake it and issue a 500 */
if (empty($code)) { $code = "500"; }
/* obviously, you can add more */
if ($code == "400") {
$status = "HTTP/1.1 400 Bad Request";
$default = "400 Bad Request - The supplied data was incorrect";
} else if ($code == "403") {
$status = "HTTP/1.1 403 Forbidden";
$default = "403 Forbidden - You are not allowed to access this resource";
} else if ($code == "404") {
$status = "HTTP/1.1 404 Not Found";
$default = "404 File Not Found - The requested file could not be found";
} else if ($code == "420") { # thanks, twitter!
$status = "HTTP/1.1 420 Enhance Your Calm";
$default = "420 Enhance Your Calm - Processing limit exceeded";
} else if ($code == "500") {
$status = "HTTP/1.1 500 Internal Server Error";
$default = "500 Internal Server Error - Something, somewhere went horribly wrong";
}
/* set the error code header, display the error to the user, and exit */
header($status);
header('Content-type: text/plain');
$message = (empty($message)) ? $default : $message;
exit($message);
// you can use .htaccess to push people towards the appropriate error code
// .htaccess
ErrorDocument 403 /error.php?code=403
ErrorDocument 404 /error.php?code=404
ErrorDocument 500 /error.php?code=500
// or you can 'include()' error.php in your application
// somefile.php - filled with pseudo code!
if (somethingWentHorriblyWrong()) {
$code = "500";
# $message doesn't have to be set, error.php is filled with generic messages
$message = "500 Internal Server Error - We ran out of sugar"; # $message doesn't have to be set, error.php is filled with generic examples
include("/error.php");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment