Thursday, January 31, 2013

How to automatically redirect between HTTP and HTTPS [PHP]

Using HTTPS allows for secure and encrypted communication between your web site and the visitor's browser. Sometimes the transition doesn't happen automatically so we need to enforce that secure communication between the server and the client, e.g. when using a shopping cart.

One way to automatically switch from HTTP to HTTPS, using PHP, is a quick check of the HTTPS key in the $_SERVER array. From the php manual on $_SERVER:
$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server.

The $_SERVER array holds a number of different key/value pairs, which can provide us with valuable information about the visitor. When available we can use this user information to serve different experiences to users from different geolocations, networks, based on their browsers, or completely block them out. So please check out the document. I am sure you will find it useful.

What we will do is check if the "HTTPS" key is present and if it has a value. If either of those is false we will construct a new URI where the URL is "https://" and the URN is the domain name plus the current request path/page.

// Redirect from HTTP to HTTPS
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);
}


Whenever I do a header redirect I like to also use the PHP language construct exit, just to ensure that nothing else is processed in case something fails with the preceding code. Also, though not necessary, you should set the header response to "301 Moved Permanently", especially if you always want to use HTTPS in search engine links.

Another way to do the same is to just check if the HTTPS key's value is set to "on".

// Redirect from HTTP to HTTPS
if ($_SERVER['HTTPS'] != "on") {
    $HTTPURI = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

    header("HTTP/1.1 301 Moved Permanently"); // Optional.
    header("Location: $HTTPURI");

    exit;
}


The nice thing about the above code is that you can use it on any page. So if a visitor has a page bookmarked or they click on a link from an email or another page they will be automatically redirected to a secure session.

No comments:

Post a Comment