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;
}
}
I have just had an issue where I was running the server using Apache mod_ssl, yet a phpinfo() and a var_dump( $_SERVER ) showed that PHP still thinks I'm on port 80.
Here is my workaround for anyone with the same issue....
The line worth noting is the SetEnv line. With this in place and after a restart, you should have the HTTPS environment variable you always dreamt of
If You use nginx as loadbalancing system check $_SERVER['HTTP_HTTPS'] == 1 other checks will be fail for ssl.
On my server (Ubuntu 14.10, Apache 2.4, php 5.5) variable
$_SERVER['HTTPS']
is not set when php script is loaded via https. I don't know what is wrong. But following lines in.htaccess
file fix this problem: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.Making my own function from reading all previous posts:
If you are using Incapsula's load balancer you'll need to use an IRule to generate a custom header for your server. I created an HTTP_X_FORWARDED_PROTO header that is equal to either "http" if the port is set to 80 and "https" if it is equal to 443.