0

I am trying to display success or failure messages using session variables. I want them to be unset once the session variable once it is accessed. Is there some kind of PHP configuration where I can do it automatically with out writing any extra code?

I want something like this:

$_SESSION['message'] = 'print success';
echo $_SESSION['message'];
unset($_SESSION['message'])// I want this to be done automatically.

Could somebody help me with this?

Jason
  • 129
  • 1
  • 5
  • 19

1 Answers1

2

You can write your own session handler and have a custom method for that. I strongly suggest Illuminate/Session, though, and use it's flash feature which keeps items in flash bag for the duration of one request only.

class Session {
   public function read($str){
      return isset($_SESSION[$str]) ? $this->deleteAndRet($str) : null;
   }
   protected function deleteAndRet($str){
      $ret = $_SESSION[$str];
      unset($_SESSION[$str]);
      return $ret;
   }
}
Tala
  • 909
  • 10
  • 29
  • so, anyway i should call some function right or is it going to be excecuted automatically ? – Jason Nov 20 '16 at 20:23
  • instead of `echo $_SESSION['message'];` you should then call `echo $session->read('message');` where `$session` is an instance of `Session` class. or you could define those methods as static and use `Session::read('message')` instead. – Tala Nov 20 '16 at 20:27
  • "unset($_SESSION['message'])// I want this to be done automatically." thats not automatic now is it ;-) –  Nov 20 '16 at 20:37