Friday, September 20, 2013

HTTP Status Codes Handling and Htaccess ErrorDocuments

Error handling using .htacces:

Here are some basic rule, use other rules if you need.

ErrorDocument 404 /Subtitle/php/error-msg.php
ErrorDocument 500 /location/php/error-msg.php
ErrorDocument 400 /location/php/error-msg.php
ErrorDocument 401 /location/php/error-msg.php
ErrorDocument 403 /location/php/error-msg.php

And the error-msg.php like this:

Here are some basic rule, use other rules if you need.

<?php
$HttpStatus = $_SERVER["REDIRECT_STATUS"] ;
  if($HttpStatus==200) {
      echo "Document has been processed and sent to you.";      
  } else if($HttpStatus==400) {
      echo "Bad HTTP request ";      
  } else if($HttpStatus==401) {
      echo "Unauthorized - Iinvalid password";      
  } else if($HttpStatus==403) {
      echo "Forbidden";      
  } else if($HttpStatus==500) {
      echo "Internal Server Error";      
  } else if($HttpStatus==418) {
      echo "I'm a teapot! - This is a real value, defined in 1998";      
  } else if($HttpStatus==404) {
      echo "Page not found here";      
  } else {
      $HttpStatus = 500;
      echo "Internal server Error";
  }
  echo "<BR>Status: ".$HttpStatus;
  exit; 
?>

Error Distribute from php file (named: mac_address.php)

If you need to show error like above one, please see below example php code:

<?php
/* UnCaught error handler */
set_exception_handler('exc_handler');

/* Error handler function */
function exc_handler(Exception $exception) {
    /* Set http status code such 404, 500 etc. */
    header("HTTP/1.1 ".$exception->getCode()." ".$exception->getMessage());
    /**
     * As 'REDIRECT_STATUS' is using in 'error-msg.php' file,
     * so we are providing this manually.
     * But it will automatically set when come from .htaccess
     */
    $_SERVER["REDIRECT_STATUS"] = $exception->getCode();
    /**
     * Including 'error-msg.php' file.
     */
    include './error-msg.php';
}
/**
 * Extentd 'Exception' to my own class 'NotFoundException'
 */
class NotFoundException extends Exception {
    public function NotFoundException($message = "Page not found") {
        throw new Exception($message, 404);
    }
}
/**
 * Throwing 'NotFoundException'
 */
//throw new NotFoundException();

/**
 * Another way to throw exception as bellow, where 
 * 'Server error' is the message and
 * '500' is the error code.
 */
throw new Exception("Server error", 500);
?>

Example output in browser (Custom 500 error using php code):

I wrote the code in mac_address.php to show 500 internal server error.














Example output in browser (404 error using .htaccess):

No file in that location named 'mac.php', .htaccess handling this internally.

No comments:

Post a Comment