Forcing SSL with PHP

Occasionally you have a registration form, login page or other php item that should be secured.  Its easy to link to something securely, however, some people play with urls ( I know, gasp ), search engines might get to the page with http, or users might somehow otherwise end up there unsecured.  Yes you can accomplish this with an .htaccess file, but sometimes you don’t have the ability to edit / create one on a server.

Add this php code to the top of your php page to have it verify and flip to secure mode if needed –

<?php
if ($_SERVER['SERVER_PORT']!=443)
{
$url = "https://". $_SERVER['SERVER_NAME'] . ":443".$_SERVER['REQUEST_URI'];
header("Location: $url");
}
?>

Conversely if yiou have to pop back to http, you can alter the code to this –

<?php
if ($_SERVER['SERVER_PORT']!=80)
{
$url = "http://". $_SERVER['SERVER_NAME'] . ":80".$_SERVER['REQUEST_URI'];
header("Location: $url");
}
?>

That’s all, just wanted to share something I found when I need this behavior on an application form.

BTW if you want to do this via .htaccess – you can use something like this –

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://domain.com/$1 [R,L]
This entry was posted in PHP. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *