Detecting if page is SSL in PHP – or – PHP SSL or NOT

In much earlier versions of PHP, it was easy to through a quick and dirty piece of code together and not worry about the php warnings – my first SSL-or-NOT detection was this simple:

if ($_SERVER['HTTPS'] != "on") {
$proto = 'http';
} else {
$proto = 'https';
}

But with the introduction of PHP 5.3 and later, this sloppy approach leads to many warnings and it is time to update the code… this is a much more secure and all-encompassing PHP code snippet which will do the job better…


if ( isset( $_SERVER['HTTPS'] ) && strtolower( $_SERVER['HTTPS'] ) == 'on' ) {
$proto = 'https';
} else {
$proto = 'http';
}

The difference is that we must first detect if the variable is set – then interrogate the variable for a specific value (and to be safe, force it lower-case before comparing to a known state of ‘on’).