Skip to content

How to check with PHP if the page is being served over HTTPS

As a follow-up to this guide on how to get an SSL certificate and configure Apache to use it, it seems logical to look for a way to detect, server-side, whether or not a specific visitor is connecting over HTTPS.

Fortunately, PHP has a trivial way to check this: the $_SERVER[‘HTTPS’] variable. It will be set to ‘on’ whenever the page is loaded over SSL. This way you could for instance force all visitors to use SSL, like this:
if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on') {
$url = 'https://'. $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
header('Location: '.$url);

Note that the isset() part is to avoid throwing an error when the page isn’t served in SSL: on most server, in this case, the $_SERVER[‘HTTPS’] variable won’t be set at all.*
The exit is important too, because otherwise the page execution will continue, so for instance if the user submitted GET data, then you’ll submit the data twice if you don’t stop the execution with the exit.

Sources (note: those sources have alternate solutions for when the above solution doesn’t work, e.g. when using PHP over fastCGI in nginx):

Posted in cryptography, web development.

0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

Some HTML is OK

or, reply to this post via trackback.

Sorry about the CAPTCHA that requires JS. If you really don't want to enable JS and still want to comment, you can send me your comment via e-mail and I'll post it for you.

Please solve the CAPTCHA below in order to fight spamWordPress CAPTCHA