I’ve seen many tutorials online that says you need to check $_SERVER['HTTPS'] if the server is connection is secured with HTTPS. My problem is that on some of the servers I use, $_SERVER['HTTPS'] is an undefined variable that results in an error. Is there another variable I can check that should always be defined?
Just to be clear, I am currently using this code to resolve if it is an HTTPS connection:
if(isset($_SERVER['HTTPS'])) {
if ($_SERVER['HTTPS'] == "on") {
$secure_connection = true;
}
}
This should always work even when
$_SERVER['HTTPS']is undefined:The code is compatible with IIS.
From the PHP.net documentation and user comments :
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_PROTOheader, but it’s much more complex to do; see latest comments below this answer.