Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Application level Session Destroy through a function in controller

I know similar questions has been asked but didn't find answer in the discussions.

I want to destroy a session through a function in the application but it is not working. Is the issue with cache or cookies. I would like to know exactly what I should do.

My code is as shown below;

        public function logoutAction(){

         $this->session->destroy();

         return $this->response->redirect('');
    }

The session id is still set when I ran the above.

When I ran this;

    $result = $this->session->destroy();
    var_dump($result); exit;

    boolean true ; 

is returned



20.3k

I use $this->session->set("whateverYouWant", null) because I had the same problem with destroy().

edited Nov '14

I have notice that $this->session->destroy(); actually is effective but within that function. the task here is to make it destroy the session outside the function



56.3k
Accepted
answer

Destroying the session doesn't destroy the session itself, but rather destroys any data associated with the session. From the documentation:

session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called.

In order to kill the session altogether, like to log the user out, the session id must also be unset. If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie() may be used for that.

For the purposes of logging out, calling $this->session->destroy() should probably be sufficient. You may also want to call session_regenerate_id() too. Remember that Phalcon's session class doesn't re-invent the wheel - it's just a wrapper for PHP's built in session functionality, so any built-in session functions also work.

After calling session destroy, you need to reload page, so dispatch user to another controoler, redirect to the home page etc.

This test shows such behaviour, and thus per controller basis you should use remove method instead of destroy.


$this->session->isStarted(); // bool(true)
$this->session->has('Connexion'); //bool(true)
$this->session->get('Connexion'); //array(2) {
  ["guid"]=>
  int(1474815656)
  ["accountID"]=>
  int(12)
}
$this->session->destroy(); //bool(true)
$this->session->has('Connexion'); //bool(true)
$this->session->get('Connexion'); //array(2) {
  ["guid"]=>
  int(1474815656)
  ["accountID"]=>
  int(12)
}
$this->session->remove('Connexion'); //NULL
$this->session->has('Connexion'); //bool(false)
$this->session->get('Connexion'); //NULL