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
/* HTTP to HTTPS Redirect
* Author: Alexandar Tzanov
* Revised: 2013-08-14
* Version: 01.00.00
* Type: A
*/
function http_https_redirect()
{
if ($_SERVER["HTTPS"] != "on")
{
header("HTTP/1.1 301 Moved Permanently"); // Optional.
header("Location: https://{$_SERVER["SERVER_NAME"]}{$_SERVER["REQUEST_URI"]}");
exit(0); // Ensure that no other code is parsed.
}
}
Version B
/* HTTP to HTTPS Redirect
* Author: Alexandar Tzanov
* Revised: 2013-08-14
* Version: 01.00.00
* Type: B
*/
function http_https_redirect()
{
if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == "")
{
$HTTPURI = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header("HTTP/1.1 301 Moved Permanently"); // Optional.
header("Location: $HTTPURI");
exit(0); // Ensure that no other code is parsed.
}
}
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. |