Detect if the webpage was fetched over SSL

Updated Dani 2 Tallied Votes 217 Views Share

Sometimes we want to know if the webpage was fetched over an SSL connection (e.g. the URL begins with https:// instead of http://). This way, if an end-user is accessing an insecure version of our site, we can redirect them to the secure version.

The following PHP function called no_ssl() returns true if the end-user is not using SSL, and false if they are. This way we can redirect them as so:

if (no_ssl())
{
    // For the purposes of HSTS, we don't want to change the HTTP_HOST
    header('Location: https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], TRUE, 301);
    exit;
}

You'll notice I made a reference to HSTS in my code comment. HSTS is a policy that, when implemented by a domain (e.g. example.com), as we have, effectively forces [compliant] web browsers to only load the secure (https) version of all resources located on that domain.

function no_ssl()
{
    return (
        // Reverse Proxy
        (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) AND $_SERVER['HTTP_X_FORWARDED_PROTO'] != 'https') OR
        (isset($_SERVER['SERVER_PORT']) AND $_SERVER['SERVER_PORT'] != 443) OR
        // We seem to be getting this when issuing cURL requests
        (isset($_SERVER['HTTP_X_SSL_CIPHER']) AND empty($_SERVER['HTTP_X_SSL_CIPHER'])) OR
        (isset($_SERVER['HTTPS']) AND $_SERVER['HTTPS'] != 'on')
    );
}