We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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



33.8k

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



125.8k
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