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

Reset Phalcon Session

Hi all,

How can I reset or clear a session in phalcon? I do not want to destroy the session, just reset if with new values.

eg.

$profile = ['firstname' => "bill", 'surname' => "gates"];  
$this->session->set('profile' , $profile);
// Bill's surname changed
$profile = $this->session->get('profile');
$profile['surname'] = "williams";
// reset session somehow? since ->remove does not work :(
$this->session->set('profile' , $profile);

Any help much appreciated.

Thanks

Looking at the API documentation always helps :) https://docs.phalcon.io/en/master/api/Phalcon_Session_Adapter_Files.html

$session->remove('profile');


22.8k

Looking at the question before posting links to documentation always helps ;-)



31.2k
Accepted
answer
edited Mar '15

Create 2 private functions i.e ( _sessionSet() and _sessionClear() )

 $this->session->set('profile', array(
        'firstname' => $newvalue['firstname'],
        'surname' => $newvalue['surname'],
    ));
}

private function _sessionClear($newvalue = null){
$this->session->set('profile', array(
        'firstname' => '',
        'surname' => '',
    ));
}

You will call _sessionSet(){ //your session set here} when setting session variables for the very first time.

$profile = ['firstname' => "bill", 'surname' => "gates"];
 $this->_sessionSet($profile);

When the profile value changes you will call _sessionClear() function which will clear the session variables and then call the session set function

$profile = $this->session->get('profile');
$profile['surname'] = "williams";

//clear the session values
$this->sessionClear()

//set new values

$this->sessionSet($profile);

Using control structures and conditional statements inside the above private functions I hope you can use the above example to achieve what you intend and maybe just work with one private function.

I'm unclear what your problem is. You want to set a session variable to a new value, and it looks like you do that. What isn't working?

Also, I'd suggest not storing arrays in the session. Not for any technical reason, it's just a pain to work with and you can just as easily store each value separately.