SSL (HTTPS) URLs and CodeIgniter

ci logo flame SSL (HTTPS) URLs and CodeIgniterI am a fan of CodeIgniter for its ease of use. I have developed several ecommerce projects using this “beautiful” framework. While working on my first ecommerce project with CodeIgniter, I faced a problem with URLs. The site was suppose to use both “http” and “https”. But with CodeIgnitor we can define one base URL, which can be either “http” or “https”. Then I came up with an idea and now I am going to share that idea with you.

What I am going to do…

We will create secure version of some functions. For this we will make changes in CodeIgnitor’s URL helper(url_helper.php), Config library (Config.php) and Config (config.php)  files. We will be creating secure version of following functions:

  • site_url()
  • base_url()
  • anchor()
  • redirect()

Lets’ start…

First we will add the following config element in the config file:

$config['secure_base_url'] = 'https://examples.com';

Then, open the url_helper.php file (system/helpers/url_helper.php) and add the following codes. You may use a separate helper file if you do not want to alter the url_helper.php file.

if( ! function_exists('secure_site_url') )
{
    function secure_site_url($uri = '')
    {
        $CI =& get_instance();
        return $CI->config->secure_site_url($uri);
    }
}
 
if( ! function_exists('secure_base_url') )
{
    function secure_base_url()
    {
        $CI =& get_instance();
        return $CI->config->slash_item('secure_base_url');
    }
}
 
if ( ! function_exists('secure_anchor'))
{
    function secure_anchor($uri = '', $title = '', $attributes = '')
    {
        $title = (string) $title;
 
        if ( ! is_array($uri))
        {
            $secure_site_url = ( ! preg_match('!^\w+://! i', $uri)) ? secure_site_url($uri) : $uri;
        }
        else
        {
            $secure_site_url = secure_site_url($uri);
        }
 
        if ($title == '')
        {
            $title = $secure_site_url;
        }
 
        if ($attributes != '')
        {
            $attributes = _parse_attributes($attributes);
        }
 
        return '<a href="'.$secure_site_url.'" ' . $attributes . '>'.$title.'</a>';
    }
}
 
if ( ! function_exists('secure_redirect'))
{
    function secure_redirect($uri = '', $method = 'location', $http_response_code = 302)
    {
        switch($method)
        {
            case 'refresh'    : header("Refresh:0;url=".secure_site_url($uri));
                break;
            default            : header("Location: ".secure_site_url($uri), TRUE, $http_response_code);
                break;
        }
        exit;
    }
}

Now, add the following code in Config.php file (system/libraries/Config.php):

    function secure_site_url($uri = '')
    {
        if (is_array($uri))
        {
            $uri = implode('/', $uri);
        }
 
        if ($uri == '')
        {
            return $this->slash_item('secure_base_url').$this->item('index_page');
        }
        else
        {
            $suffix = ($this->item('url_suffix') == FALSE) ? '' : $this->item('url_suffix');
           return $this->slash_item('secure_base_url').$this->slash_item('index_page').preg_replace("|^/*(.+?)/*$|", "\\1", $uri).$suffix;
        }
    }

Now what we have…

Now what we have? We have secured versions of those function. You may now use them as their insecured version. Enjoy coding ;).

share save 120 16 SSL (HTTPS) URLs and CodeIgniter

26 thoughts on “SSL (HTTPS) URLs and CodeIgniter”

  1. Sometimes we need to redirect external site. I wrote a function for CI to redirect external site. Hope this will help you.

    if ( ! function_exists('redirect_external'))
    {
         function redirect_external($uri = '', $method = 'location', $http_response_code = 302)
         {
              switch($method)
              {
                   case 'refresh' :     header("Refresh:0;url=".prep_url($uri));
                                            break;
                   default :    header("Location: ".prep_url($uri), TRUE, $http_response_code);
                                  break;
              }
              exit;
         }
    }
  2. hi sajjad vai,
    on my site there is need to user http and https. and my model files are not working. i put those files on those place. i really dont know how it will work? please do reply. i badly need help.
    Thanks
    Sabrina

  3. I have base url dynamically defined in my apps as

    $config['host_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
    $config['host_url'] .= "://".$_SERVER['HTTP_HOST'];
    $config['base_url'] = $config['host_url'] . str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);

    AND for SSL redirect I use a utility helper

    if (! function_exists('ssl_redirect'))
    {
        function ssl_redirect()
        {
            if ($_SERVER["SERVER_PORT"] != 443)
            {
                redirect(str_replace("http://", "https://" , current_url()), "refresh");
            }
        }
    }

    That redirects the current url to ssl url. It’s called in the controller you want to have only ssl request like payment pages. For generating anchor if you have the base_url dynamically generated like stated above, anchors are generated with https if the pages are in https. So don’t need the secure anchor. Hope this helps!

  4. Thanks Mahbub for sharing.

    But I don’t agree with “So don’t need the secure anchor”. Your solution will make all anchors secure which is good for 100% secure site.

    Think of a situation, you have a secure page and in that page you need some links with “http”. Again in a “http” page you need some links with “https”. In these situations my solution works fine.

  5. Yes, true that links you can build both for http and https. But Normally in some pages we want to make sure that user can’t but use the ssl url. So you put the helper function ssl_redirect() in the controller which will redirect 301 to the same url but with ssl. Like in payment pages we want to make sure that it’s not http but https. Perhaps both we’d both your and my solution as needed.

  6. Thanks for posting this! It helped me out on a project.

    I should point out there a couple of things that need to be fixed. In your code above, the last line of the function secure_anchor() in your url helper is missing a couple of single quotes. It should read:

    return '<a href="'.$secure_site_url.'" rel="nofollow">'.$title.'</a>';

    Also, it would be better not to edit the core CI files. One day someone else might upgrade CI and your ssl suddenly doesn’t work!. Instead put the url_helper code in a file called MY_url_helper.php and store it in system/application/helpers/

    Likewise, instead of adding code to the core Config.php library, put it in system/application/libraries/MY_Config.php – and follow the instructions for extending native libraries found at this url:

    http://codeigniter.com/user_guide/general/creating_libraries.html

    in MY_Config.php you would wrap the function with this code:

    class MY_Config extends CI_Config {
     
    }
  7. Martin, thanks for your correction and suggestions. I was thinking to upgrade the code as you said because I myself faced this problem while upgrading to latest CI version. I am a little bit busy now but I will work on it and share with others.

  8. Thanks Mohammad and Mahbub — I recently used this for a school project and it works great; I extended the base url_helper as Martin suggested.

    One other thing that came in handy was overriding CI’s base_url() method in MY_url_helper; other libraries like Template call base_url() when you do things like add_js() or add_css(), which causes warnings to pop up in IE if you’re on a secure page. This was the fix:

    function base_url() {
       $framework =& get_instance();
     
       if (isset($_SERVER['HTTPS'])) {
          return $framework->config->slash_item('secure_base_url');
       } else {
          return $framework->config->slash_item('base_url');
       }
    }
  9. @Mohammed Yes, please change this post so show EXTENDING the helper (url_helper.php) and core (config.php) files, instead of editing them. I would hate new CI programmers to come here and do it the way it is shown in your post.

    Otherwise, thank you for your code! It was very helpful!

  10. Hi,

    secure_site_url is not working for me.it’s doesnt show anything after the function called.
    or its showing blank page.why?

  11. Hi..
    Is there any changes for the CodeIgniter version 2.1 and greater.
    Currently this is not working for me.

  12. My pages are not showing when I am using https in my url.
    Any suggestion or any change I should made in my CI_2.0.3 config file.
    thanks in advance.

Leave a Reply

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

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=""> <strike> <strong>