Titan Fusion

Alexandar Tzanov's Personal Blog

Function: http_https_redirect


The http_https_redirect PHP function will redirect a visitor from HTTP to HTTPS.

The best location to place the function would be at the beginning of your file. Before the rest of the page code, or right after anything that should take place no matter what, e.g. page hit counter.

You will find two different versions of the same function. They both perform the same action. They just use a different approach.

Source Code

Version A

  1. /* HTTP to HTTPS Redirect
  2.  * Author: Alexandar Tzanov
  3.  * Revised: 2013-08-14
  4.  * Version: 01.00.00
  5.  * Type: A
  6.  */
  7.  
  8. function http_https_redirect()
  9. {
  10.     if ($_SERVER["HTTPS"] != "on")
  11.     {
  12.        header("HTTP/1.1 301 Moved Permanently");    // Optional.
  13.        header("Location: https://{$_SERVER["SERVER_NAME"]}{$_SERVER["REQUEST_URI"]}");
  14.  
  15.        exit(0); // Ensure that no other code is parsed.
  16.     }
  17. }

Version B

  1. /* HTTP to HTTPS Redirect
  2.  * Author: Alexandar Tzanov
  3.  * Revised: 2013-08-14
  4.  * Version: 01.00.00
  5.  * Type: B
  6.  */
  7.  
  8. function http_https_redirect()
  9. {
  10.     if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == "")
  11.     {
  12.         $HTTPURI = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  13.  
  14.         header("HTTP/1.1 301 Moved Permanently");   // Optional.
  15.         header("Location: $HTTPURI");
  16.  
  17.         exit(0);    // Ensure that no other code is parsed.
  18.     }
  19. }

Usage

http_https_redirect();

Parameters

Name Definition Default Value
N/A N/A N/A

Return

There is no return.

Examples

include 'function.http_https_redirect.php';
 
http_https_redirect();

The above code will include the function file into the page and the function call will result in redirecting the visitor of the current page to the same page but using SSL HTTPS.

Revision History

Date Version Changes
2013-08-14 01.00.00 Initial release.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.