How to redirect http to https in codeigniter

HTTP to HTTPS in Codeigniter

Posted  258 Views updated 10 months ago

Sure, I knew my customer was gonna yell if the green padlock wasn't up there. There's so much scare about it recently in my region like "no green padlock, then it's a phishing site"... let me spare you the crap.

Here was the glorious fix I found in StackOverflow 

Step 1. Open config file from location application/config/config.php and enable or set hooks to true like this:

$config['enable_hooks'] = TRUE;

Step 2. Then create a new file named hooks.php inside the config folder (i.e. application/config/hooks.php) and add the following code in it:

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

Step 3. Now create a new directory named hooks (mine had hooks folder already) inside the application folder (i.e. application/hooks) and then create a new file named ssl.php inside the hooks folder (i.e. application/hooks/ssl.php).

Add the following code in the ssl.php file:

function redirect_ssl() {
    $CI =& get_instance();
    $class = $CI->router->fetch_class();
    $exclude =  array('client');  // add more controller name to exclude ssl.
    if(!in_array($class,$exclude)) {
        // redirecting to ssl.
        $CI->config->config['base_url'] = str_replace('http://', 'https://', $CI->config->config['base_url']);
        if ($_SERVER['SERVER_PORT'] != 443) redirect($CI->uri->uri_string());
    } else {
        // redirecting with no ssl.
        $CI->config->config['base_url'] = str_replace('https://', 'http://', $CI->config->config['base_url']);
        if ($_SERVER['SERVER_PORT'] == 443) redirect($CI->uri->uri_string());
    }
}

 

Step 4. do not forget to change your base_url in application/config/config.php like below to https URL.

                    $config['base_url'] = 'https://www.my-site.com/';

Step 5. Make sure you have a valid SSL certificate for your domain.

 

Hope this helped. Have a blessed day.


Your reaction?

0
LOL
1
LOVED
0
PURE
0
AW
0
FUNNY
0
BAD!
0
EEW
0
OMG!
0
ANGRY
0 Comments