Logout codeigniter

2019-02-13 18:04发布

问题:

I have a logout controller in codeigniter :

<?php

class Logout extends MY_Controller {

    function index()
    {

        $this->session->sess_destroy();
        redirect('index.php');
    }
}

This logs me out but when i call another controller after logging, like "/site/addnewpost", this just logs me in again, as if the sassion had not been destroyed previously. Why is this happening?

回答1:

Follow ALex's suggestion, but using CI code:). What I mean, try unsetting each session data individually. I read once about an issue in version 2.0.3 I think, but I don't remember now and I don't have time to search for the reference. It's in their forum, though, and the suggestion was the same: unset each session element one by one.

$this->session->unset_userdata('data_one');
$this->session->unset_userdata('data_two');
$this->session->unset_userdata('data_three');
$this->session->unset_userdata('data_one');
$this->session->sess_destroy();
redirect('home','refresh');  // <!-- note that
//you should specify the controller(/method) name here

You need to redirect because CI's session are just cookies, not the native php session array.

Another thing...make sure the fault isn't in your login methods, which logs you in no matter if you succesfully logout or not!



回答2:

Try explicitly delete items like this:

$this->Session->delete('User');
$this->Session->destroy();
$this->Cookie->delete("User");
$this->Cookie->destroy();
$this->Auth->logout();
$this->redirect('whereever');


回答3:

My problem had to do with caching on the server side. The quickest I could fix it was by appending random text to the logout link:

<?php
    $this->load->helper('string');
    echo anchor('/home/logout/'.random_string(), 'logout');
?>

home/logout contained the same code as function index in the question.

Just so you know the redirect('/', 'refresh') did not work for me, but I again I did a quick test.

I am guessing that the random_string() method can be replaced by outputting headers that force cache to be cleared etc. As you have probably guessed, I can't do that right now as I am super busy. Maybe later.



回答4:

You can also try manually setting your "logged_in" or whatever you called the session to false. Then, destroying all other session data.

    $this->session->set_userdata('logged_in', FALSE);
    $this->session->session_destroy();
    redirect('index');


回答5:

first we have to load session library to deal with session than unset the sessionID and destroy the session. I am using this code to unset my session and secure logout.

$this->load->library('session');
$this->session->set_userdata('user_id', FALSE);
$this->session->sess_destroy();
$this->load->view('your URL');