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]
Code it right
theCodeDog
theCodeDog

posted in PHP by Jonathan

Follow comments via the RSS Feed | Leave a comment | Trackback URL

Leave Your Comment

 
Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org