Sunday, December 20, 2020

Best Way to redirect http to https in CodeIgniter

Follow the below steps to enable http to https on your codeIgnitor 3.x using.

STEP 1. Config changes :- Go to “application/config/config.php” and enable or set hooks to true.

$config['enable_hooks'] = TRUE;

STEP 2: Create a new file named hooks.php in “application/config/hooks.php” if not exists and if its already exists just add below code in hooks.php

$hook['post_controller_constructor'][] = array(

                                'function' => 'redirect_ssl',

                                'filename' => 'ssl.php',

                                'filepath' => 'hooks'

                                );

STEP 3: Now create a new directory with named “hooks” under application directory and then create new file named “ssl.php” in “application/hooks/ssl.php” and add below code to “ssl.php”

function redirect_ssl() {

    $CI =& get_instance();

    $class = $CI->router->fetch_class();

    $exclude =  array('client');  // add all your controllers 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());

    }

}


Credits: https://stackoverflow.com/users/2261069/preetham-hegde

No comments:

Post a Comment

Please Comment Here!

How to backup and download Database using PHP

< ?php $mysqlUserName = 'databaseusername' ; $mysqlPassword = 'databasepassword' ; $mysqlHostNa...