Always redirect to HTTPS with Codeigniter

0

I have an application with CodeIgniter and I always have to force the connection to always redirect to https .

I did this:

  • Changed within config\config.php line $config['enable_hooks'] to TRUE .
  • Within config\hooks.php I added the lines.

    $hook['post_controller_constructor'][] = array(
        'function' => 'redirect_ssl', 
        'filename' => 'ssl.php', 
        'filepath' => 'hooks'
    );
    
  • In the hooks folder, I created the file ssl.php with the following function:

    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());
        }
    }
    
  • After performing the test the page up and redirected to https:// more comes the error in Chrome:

      

    This page is not working
      Excessive redirection on myite.com   Please try to clear your cookies.   ERR_TOO_MANY_REDIRECTS '

        
    asked by anonymous 24.07.2017 / 20:49

    1 answer

    1

    Oops. It is safer for you to do the redirection in .htaccess and also in CodeIgniter. Htaccess 01 - Create a file named ".htaccess" 02 - And put inside of him RewriteEngine On RewriteCond% {SERVER_PORT} 80 RewriteRule ^ (. *) $ link $ 1 [R, L]

    But it's also interesting to do in codeigniter following the instructions in this link: link

        
    24.07.2017 / 21:02