Easy SSL redirection in CodeIgniter

One of the most common requests I see from clients is shopping cart and ordering functionality for their website. To properly implement, you need SSL security, which can sometimes be a little hard to work with in CodeIgniter – there are times when you may a few pages served to the user securely, a few securely and insecurely, and everything else normally. With a few lines of code, this can be done.
Step one: open up your main site’s application/config/config.php file. around line 17 you should see

$config['base_url'] = 'http://www.yoursite.com/';

Let’s modify this a bit to:

$proto = "http" . ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "s" : "") . "://";
$config['base_url'] = $proto . 'www.yoursite.com/';

Now the basic assumption here is that you are using the URL helper to generate URL’s across your site using base_url() and site_url(‘xxxx’) functions. If you are, this little snippet will ensure that all images, stylesheets, etc., are served to on the requesting page securely. This helps alleviate the “do you want to only display the secure portions of this website” popup you see from time to time.

While you’re in application/config/config.php, Let’s enable hooks, which should be around line 98:

$config['enable_hooks'] = TRUE;
$hook['post_controller_constructor'][] = array(
                                'function' => 'check_ssl',
                                'filename' => 'ssl.php',
                                'filepath' => 'hooks'
                                );

This establishes a hook entry point which takes place immediately after your controller is instantiated, but prior to any method calls happening.

Next, in your application/hooks folder, create a file called ssl.php and in it place:

function check_ssl()
{
    $CI =& get_instance();
    $class = $CI->router->fetch_class();

    $ssl = array('checkout', 'cart');
    $partial =  array('login','registration');

    if(in_array($class,$ssl))
    {
        force_ssl();
    }
    else if(in_array($class,$partial))
    {
        return;
    }
    else
    {
        unforce_ssl();
    }
}

function force_ssl()
{
    $CI =& get_instance();
    $CI->config->config['base_url'] = str_replace('http://', 'https://', $CI->config->config['base_url']);
    if ($_SERVER['SERVER_PORT'] != 443) redirect($CI->uri->uri_string());
}

function unforce_ssl()
{
    $CI =& get_instance();
    $CI->config->config['base_url'] = str_replace('https://', 'http://', $CI->config->config['base_url']);
    if ($_SERVER['SERVER_PORT'] == 443) redirect($CI->uri->uri_string());
}

Note: for the sake of this example, I’ve place the force_ssl() and unforce_ssl() functions in the hooks.php file. Normally however, these are in my ssl_helper.php file, which is one of my auto-loaded helpers for what I use as my CI project base.

To get this working on your site, change the array values in $ssl and $partial to match your site’s needs. $ssl should contain an array of the controller names that must be served securely on your site. In this example, any attempt to access a method within my checkout or cart controllers will automatically redirect back to the same page (with https) if SSL is not enabled in the current request.

$partial is a little different. Controller names specified in $partial can be served securely or insecurely. Here’s the reasoning behind this: On sites I build, I have my registration and login forms set up in a “userControls” folder so I can use them on multiple locations across sites. If you’re simply coming to the site and wish to register, then you wouldn’t really need SSL on this. However, if you’re attempting to place an order, step 1 of my checkout process is always “log-in, or register” (for those not already logged-in). As such, calls to my login and register controllers are sometimes done over SSL, and sometimes done over regular HTTP. The advantage here is that the user can now ‘securely’ login and continue with their order.

About the author

PHP | MVC | Codeignitor | Zend | Yii | Smarty | Android | Laravel Expert Senior Software Developer.I love my job and feel happy to working on new ideas and technologies.

Leave a Comment

Comment (required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Name (required)
Email (required)