Expect the unexpected

I have seen many examples lately of “newbie” help posts where the code given, though technically correct, does not suit a wide range of situations. The most recent example of this I found on DZone’s PHP Zone. I read this post, and couldn’t help but have to comment on the limited view that was embraced by the original poster. Yes, checking for port 443 use will indeed work to determine if the incoming request is SSL encrypted, but only provided your server is using the standard ports. I work with a situation where when we have a client site with an installed SSL certificate, we place our beta server on a non standard port with the same domain name as the live site. The allows us to ensure that there are no issues with the certificate while not having to purchase or bill our clients for an additional certificate. For this situation we use PHP’s built in support for detecting HTTPS communication.

if ($_SERVER['HTTPS'] == '' || $_SERVER['HTTPS'] == 'off') {
    // redirect here to the proper hostname, port number and page
    header("Location: https://{$_SERVER['HTTP_HOST']}:{$secure_port}
              {$_SERVER['REQUEST_URI']}");
    exit();
}

This code will support you in re-directing your non HTTPS communication to HTTPS when using non-standard ports, you will need to supply the $secure_port variable to ensure that redirection goes to the proper target.

Leave a Reply

Musings From the World of PHP