Error: while login and logout using codeigniter [d

2019-06-01 23:59发布

问题:

This question already has an answer here:

  • Codeigniter pressing logout button and disable the back browser button 4 answers

The login and logout is working fine but, after getting logout from the page im still able to access that page, for example in url if i use as codeigniter_try/index.php/Home/backend its displaying the page which should not happen, i mean to say it should display only when i loggedin with the username and password. what issue im facing here can any one guide me ?

This is my Controller.php

//-------this is Login method --------
public function login()
{
    if($this->input->post('login'))
    {
        $username=$this->input->post('username');
        $password=md5($this->input->post('password'));
        $query=$this->db->query("select * from login where username='".$username."' and password='$password'");
        $row = $query->num_rows();
        if($row)
        {
            $newdata=array(
                'username' => $this->input->post('username'),
                'password' => md5($this->input->post('password')),
                'is_logged_in'=>TRUE
            );
            $this->session->set_userdata($newdata);
            redirect('Home/Backend');
        }
        else
        {
            $data['error']="<h3 style='color:red'>Invalid login details</h3>";
        }   
    }

    $this->load->view('login',@$data);      
}

//---------this is Logout method --------
public function logout()
{
    $this->session->unset_userdata($newdata);
$this->session->sess_destroy();
redirect('Home/login');
}

//-------Backend page---------

     public function Backend()
   {
     $this->load->view('backend');
     }

回答1:

Hope this will help you :

your logout method should be like this :

public function logout()
{
    $this->session->sess_destroy();
    redirect('Home/login');
} 

Your Backend should be like this : you have to check it in all controllers

public function Backend()
{ 
   if (! $this->session->userdata('is_logged_in')) redirect('Home/login'); 
   $this->load->view('backend'); 
} 

For more : https://www.codeigniter.com/user_guide/libraries/sessions.html#destroying-a-session



回答2:

unset_userdata() can be used to remove it, by passing the session key.

so, logout function will be change like this.

public function logout()
{
    $this->session->unset_userdata('username');
    $this->session->unset_userdata('password');
    $this->session->unset_userdata('is_logged_in');

/*
Or

    $array_items = array('username' , 'password' , 'is_logged_in');
    $this->session->unset_userdata($array_items);
*/

    $this->session->sess_destroy();
    redirect('Home/login');
}