Search code examples
codeignitercodeigniter-2

How to make user logout ,when he try to enter register URL?


I'm trying to make when user is logged in, and enters url for registration, to be logged out and show registration form.

In my controller method for registration I added this but it's not working:

 public function register()
 {
        if($this->session->userdata('is_logged_in')) {
            $this->session->sess_destroy();
            redirect('auth/logout');
        }
        //form validation
        if ($this->form_validation->run()==FALSE)
        {
            $this->signup();
        }
        else 
        {  
          //login
        }
  }

  public function signup()
  {

        $data['dynamic_view'] = 'auth/register_form';
        $this->load->view('templates/main',$data);  
  }

My login method is

 public function login ()
    {

        $this->form_validation->set_rules('username', 'username', 'trim|required');
        $this->form_validation->set_rules('password', 'password', 'trim|required'); 


        if ($this->form_validation->run()==FALSE)
        {

            $this->index();
        }
        else 
        {
            if ($user = $this->auth_model->login()) {
                if(count($user) > 0 )    
                {
                    $this->load->library('session'); 

                     $data = array(
                        'username' => $user['username'],
                        'user_id' => $user['user_id'],
                        'is_logged_in' => TRUE

                    );
                    $this->session->set_userdata($data);         

                    redirect('home');
                }
            }
            else
            {   

                 $this->index();
            }
        }
    }

Solution

  • Try $this->session->unset_userdata('is_logged_in');, no need to destroy whole session. I would do something else in such case, I would just redirect to main page and set flashdata message.

    Also there could be a problem with loading library. Try to add session library to autoload.php in application/config.