Graphic and Web Design + Development

Dynamically assigning https for SSL

Posted by on Jun 8, 2011 in Blog | 0 comments

Dynamically assigning https for SSL

Working on an e-commerce site for a client, and I started thinking about the best way to define which pages would be routed through the SSL encryption. I could make the whole site as https, but I’d rather avoid the performance trad-off. Instead, what I do is at the top of my files have a variable when it requires SSL

$requireSSL = true;

Use a variable, or define a constant, whatever you want to do. And at the top of my header.php I have

if($requireSSL && $_SERVER['SERVER_PORT'] != 443) {
   header("HTTP/1.1 301 Moved Permanently");
   header("Location: https://".$_SERVER['HTTP_HOST']."/".$_SERVER['REQUEST_URI']);
  die(); //incase output buffering is on
}
if(!$requireSSL && $_SERVER['SERVER_PORT'] == 443){
   header("HTTP/1.1 301 Moved Permanently");
   header("Location: http://".$_SERVER['HTTP_HOST']."/".$_SERVER['REQUEST_URI']);
   die(); //incase output buffering is on
}

So when it comes to the file you want to require SSL on you just have a file like myaccount.php

<?php
    $requireSSL = true;
    require_once("header.php");
    echo "Content";
?>

This will make it easy to set any pages with user input as SSL and redirects back to http:// on pages where it is not required (it is a bit faster on http).

 

Leave a Comment