CodeIgniter SSL URLs

Setup and Usage

For a while I have been wanting a nice way to choose between generating HTTP or HTTPS URLs with CodeIgniter while changing code in as few places as possible.

This particular solution involves adding 5 extra configuration options:

<?php
//  HTTPS base URL
$config['https_base_url'] = "https://mysite.com/";
//  Prefixes for forcing ssl/nossl/auto on urls
$config['https_ssl_trigger'] = "ssl:";      //  Always use https
$config['https_nossl_trigger'] = "nossl:";  //  Always use http
$config['https_auto_trigger'] = "auto:";    //  Use whatever was used in the current request
//  Default mode
$config['https_default_trigger'] = $config['https_nossl_trigger'];
?>

Hopefully this should make it useful yet completely configurable so that it can be used anywhere. The other part of the solution is the extending of CI_Config to overload the site_url() method with my own version that handles these 'triggers'. Any function that uses site_url() on a URL can now use URIs in the form <trigger><uri>, where the trigger is optional - this means this functionality is extended to most of the URL, Form and other miscellaneous helper functions.

If you want to be able to use base_url() to get the SSL URL (or automatically choose which one) replace the base_url() function in url_helper.php (usually at system/helpers/url_helper.php) with the following:

<?php
/**
 * Base URL
 *
 * Returns the "base_url" item from your config file
 *
 * @access  public
 * @param   string  Which base url to get - ssl, nossl or auto
 * @return  string
 */
function base_url($mode = null)
{
    $CI =& get_instance();
    switch ( $mode )
    {
    case null:
        switch ( $CI->config->item('https_default_trigger') )
        {
        case $CI->config->item('https_nossl_trigger'):
            return $CI->config->slash_item('base_url');
        case $CI->config->item('https_ssl_trigger'):
            return $CI->config->slash_item('https_base_url');
        default:
            return $CI->config->ssl ? $CI->config->slash_item('https_base_url') : $CI->config->slash_item('base_url');
        }

    case 'nossl':
        return $CI->config->slash_item('base_url');

    case 'ssl':
        return $CI->config->slash_item('https_base_url');

    default:
        return $CI->config->ssl ? $CI->config->slash_item('https_base_url') : $CI->config->slash_item('base_url');
    }
}
?>

Download

The following file needs to be put in your <appdir>/libraries/ directory:

system/application/libraries/MY_Config.php

Also, you will need to add the above options to your <appdir>/config/config.php.

Bugs/Suggestions

I'm not perfect, and I doubt this code is either - please feel free to contact me with any bugs or suggestions.

Last modified April 13th, 2008 at 2:50 a.m.