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);
exit;
}

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.

Please solve the CAPTCHA below in order to fight spamWordPress CAPTCHA