SSL (HTTPS) URLs and CodeIgniter

ci_logo_flameI 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

29 Comments

  • By Jidni, October 27, 2008 @ 4:55 pm

    Great work sajjad vi. I am just looking around for this. It will help me a lot 🙂

  • By Mohammad Sajjad Hossain, October 27, 2008 @ 6:30 pm

    Thank you Jilani bhai.

  • By Arafat Rahman, October 28, 2008 @ 11:09 am

    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;
         }
    }
  • By Mohammad Sajjad Hossain, October 28, 2008 @ 11:38 am

    Thank you Arafat for sharing your code.

    Also I would like to add, this function can be added to the url_helper.php file like the other functions I have shown.

  • By Ivar, November 19, 2008 @ 3:23 pm

    Thanks Arafat. That is exactly what I was browsing around for! Good work!

  • By Milon, November 28, 2008 @ 11:29 am

    Sajjad Vai Thank you.

    Please give a option also download those file.

  • By Mohammad Sajjad Hossain, November 28, 2008 @ 12:01 pm

    Milon Bhai,
    You don’t need to download those files. Just put these codes in those files. If you face any problem let me know.

    Thank you for visiting my site. 🙂

  • By sabrina, February 6, 2009 @ 12:08 pm

    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

  • By Mohammad Sajjad Hossain, February 6, 2009 @ 10:51 pm

    Hi Sabrina,
    I have not faced such problem and many of my sites using these are working fine. Can you tell me the problems in details? If possible you may share the controller and model code.

  • By Mahbub, May 21, 2009 @ 4:14 pm

    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!

  • By Mohammad Sajjad Hossain, May 22, 2009 @ 7:13 am

    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.

  • By Mahbub, May 27, 2009 @ 5:39 pm

    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.

  • By Martin Evans, September 29, 2009 @ 7:56 am

    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 {
     
    }
  • By Mohammad Sajjad Hossain, September 29, 2009 @ 9:55 am

    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.

  • By Max Fellows, December 3, 2009 @ 10:35 am

    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');
       }
    }
  • By pk, January 28, 2010 @ 5:20 pm

    Here’s a simple CodeIgniter SSL (HTTPS) Helper which i wrote.

  • By Sean Gates, July 10, 2010 @ 9:56 am

    @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!

  • By prog3712, December 5, 2011 @ 11:24 pm

    Great!!! It works perfectly!!
    The Max Fellows solution works great for me.

  • By Timo, July 21, 2012 @ 2:47 am

    Thanks for this great solution, that is exactly what I’ve been looking for!! 🙂

  • By rob, November 16, 2012 @ 5:30 pm

    about which version are u talking….

  • By rob, November 16, 2012 @ 5:31 pm

    of CodeIgniter..

  • By Jagesh, February 25, 2013 @ 4:29 pm

    Hi,

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

  • By Anuja, August 21, 2013 @ 4:54 pm

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

  • By Sakil, October 2, 2013 @ 2:56 pm

    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.

  • By Mohammad Sajjad Hossain, October 2, 2013 @ 3:00 pm

    Do you have SSL enabled in your site?

  • By Gyan Shrestha, July 17, 2014 @ 5:28 pm

    i have tried all what you mentioned above it doesnot work. It shows the error

    Not Found

    The requested URL /dashboard was not found on this server.

    Apache/2.2.15 (CentOS) Server at temonakun.temonalab.com Port 443

    It doesnot take the base_url

  • By Ivan, September 2, 2015 @ 8:03 pm

    Hello,

    I need unsecured version of this function, from HTTPS to HTTP, for social shares because they don’t use 301 redirection. Im not a programmer so please can you help me

    Thanks in advance

  • By Serge, November 25, 2015 @ 2:18 am

    More simplest way to enable allow HTTPS connexion on CodeIgniter :

    Past this on “config.php” file a the place of line “$config[‘base_url’] = …”

    // Detecting if request is HTTPS (work also with loadbalanced/proxy)
    $isSecure = false;
    if (isset($_SERVER['HTTPS']) &amp;&amp; $_SERVER['HTTPS'] == 'on') {
      $isSecure = true;
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) &amp;&amp; $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) &amp;&amp; $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
      $isSecure = true;
    }
     
    if ($isSecure) {
      $config['base_url']	= 'https://www.yoursite.xxx/';
    } else {
      $config['base_url']	= 'http://www.yoursite.xxx/';
    }

Other Links to this Post

RSS feed for comments on this post.

Leave a comment

blog