Custom Error Pages in .htaccess


/ Published in: PHP
Save to your folder(s)

This example shows you how to define custom error pages in .htaccess file and also how to display the error page on your site. You may create separate files for each error, described in Sample 1 or just create the one PHP file for Sample 2. Here the PHP template for dealing with any sort of error, if you want to keep it simple:


Copy this code and paste it in your HTML
  1. # Sample 1: redirect errors to html files
  2. ErrorDocument 400 /400.html
  3. ErrorDocument 401 /401.html
  4. ErrorDocument 403 /403.html
  5. ErrorDocument 404 /404.html
  6. ErrorDocument 405 /405.html
  7. ErrorDocument 408 /408.html
  8. ErrorDocument 414 /414.html
  9. ErrorDocument 500 /500.html
  10. ErrorDocument 502 /502.html
  11. ErrorDocument 504 /504.html
  12.  
  13. # Sample 2: redirect errors to PHP file
  14. ErrorDocument 400 /error.php?q=400
  15. ErrorDocument 401 /error.php?q=401
  16. ErrorDocument 403 /error.php?q=403
  17. ErrorDocument 404 /error.php?q=404
  18. ErrorDocument 405 /error.php?q=405
  19. ErrorDocument 408 /error.php?q=408
  20. ErrorDocument 414 /error.php?q=414
  21. ErrorDocument 500 /error.php?q=500
  22. ErrorDocument 502 /error.php?q=502
  23. ErrorDocument 504 /error.php?q=504
  24.  
  25. <?php
  26. // @file error.php
  27. $error_msg = array();
  28. if(isset($_GET["q"]) && is_numeric($_GET["q"])){
  29. $status = array(
  30. 400 => array("400 Bad Request", "Your syntax is wack."),
  31. 401 => array("401 Login Error", "Please try again."),
  32. 403 => array("403 Forbidden", "This be private homey."),
  33. 404 => array("404 Missing", "Clearly this doesn't exist."),
  34. 405 => array("405 Method Not Allowed", "Method Not Allowed."),
  35. 408 => array("408 Request Timeout", "Upgrade your browser."),
  36. 414 => array("414 URL To Long", "Is that a URL in your pants?"),
  37. 500 => array("500 Internal Server Error", "AHHHhhh my server is down!"),
  38. 502 => array("502 Bad Gateway", "The server is acting all crazy."),
  39. 504 => array("504 Gateway Timeout", "I'm sorry, I'm afraid I can't do that."),
  40. );
  41. $error_msg = $status[$_GET["q"]];
  42. }
  43.  
  44. if(!empty($error_msg)){
  45. foreach ($error_msg as $err) echo $err."<br>";
  46. }else{
  47. echo "Something went wrong.";
  48. }
  49. ?>

URL: http://www.apphp.com/index.php?snippet=htaccess-custom-error-pages

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.