How to find out if you’re using HTTPS without $_SERVER[‘HTTPS’]

This should always work even when $_SERVER['HTTPS'] is undefined:

function isSecure() {
  return
    (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
    || $_SERVER['SERVER_PORT'] == 443;
}

The code is compatible with IIS.

From the PHP.net documentation and user comments :

  1. Set to a non-empty value if the script was queried through the HTTPS protocol.
  2. Note that when using ISAPI with IIS, the value will be “off” if the request was not made through the HTTPS protocol. (Same behaviour has been reported for IIS7 running PHP as a Fast-CGI application).

Also, Apache 1.x servers (and broken installations) might not have $_SERVER['HTTPS'] defined even if connecting securely. Although not guaranteed, connections on port 443 are, by convention, likely using secure sockets, hence the additional port check.

Additional note: if there is a load balancer between the client and your server, this code doesn’t test the connection between the client and the load balancer, but the connection between the load balancer and your server. To test the former connection, you would have to test using the HTTP_X_FORWARDED_PROTO header, but it’s much more complex to do; see latest comments below this answer.

Leave a Comment