Search code examples
codeignitercodeigniter-2codeigniter-urlcodeigniter-routing

CodeIgniter routing issue, advice how to do it


I'm not CI programmer, just trying to learn it. Maybe this is wrong approach, please advice.

my controller(not in sub directory) :

class Users extends CI_Controller {

    function __construct() {
        parent::__construct();
    }

public function index($msg = NULL) {

        $this->load->helper(array('form'));

        $data['msg'] = $msg;

        $this->load->view('user/login' , $data);

    }

   public function process_logout() {
        $this->session->sess_destroy();
        redirect(base_url());
    }

}

And a route for login :

$route['user/login'] = 'users/index';

Problem is when I wanna logout, it shows me 404 because I do not have it in my route :

$route['user/process_logout'] = 'users/process_logout';

and in my view I put <a href="users/process_logout">logout</a>

When I add that, it works, and that is stuppid to add a route for everything. What I'm I doing wrong, please advice.

Thank you


Solution

  • Don't know why you are trying to implement login feature in index() function. However since you said you are learning CI I'm telling something about _remap() function.

    Before that. You can try the following routing:

    $route['user/:any'] = 'users/$1';
    $route['user/login'] = 'users/index';
    

    If you want to take value immediately after controller segment you need to use _remap() function and this function may be solve your routing problem, i mean you don't need to set routing. Lets implement your code controller 'users' using _remap() function.

    class Users extends CI_Controller {
    
        private $sections = array('login', 'logout');
    
        function __construct() {
            parent::__construct();
    
        }
    
       public function _remap($method)
       {
            $section = $this->uri->segment(2);
    
            if(in_array($section, $this->sections))
                call_user_func_array(array($this, '_'.$section), array());
    
            else show_404(); // Showing 404 error
       }
    
       private function _login() 
       {
            $msg = $this->uri->segment(3);
    
            $this->load->helper(array('form'));
            $data['msg'] = $msg;
            $this->load->view('user/login' , $data);
        }
    
       public function _logout() {
            $this->session->sess_destroy();
            redirect(base_url());
        }
    
    }