Thursday, June 30, 2016

Custom Session Expire Time for individual session variable. | How do I expire a PHP session after given time?

session handling


Laravel has a very well documentation for Session. Those who're not aware of it, just go through first. In this session I'm gonna discuss about how to set timer for individual session variable. Laravel has a default session lifetime in config/session.php.  That's for general purpose means it's for overall session lifetime for the whole application. But what if you need to put a custom timer in specific sessions? Means after certain time it'll unset or kill that session. So today I'm gonna writing about it.

In Laravel, we can save or store a session by following way:

 Session::set('name', $name);
Now let's put another session variable with  the required one. Such as,
 Session::set('LAST_ACTIVITY',time());

Now suppose we want to show this 'name' session in our view page, We can show show the Session by the following Way:
{{Session::get('name')}}
Now Let's say we gonna store the session for one minute. Means it'll show the session variable for 1 minute for in our view page. How we can do it? It's quite easy. What we need to do is just compare the LAST_ACTIVITY  session variable with time() method, so when it's greater than 60 means 1 minute it'll remove the session by Session::forget() method. So what we stored in session after 1 minute if we load the page we won't see that session in our view page.

@if (Session::get('LAST_ACTIVITY') && (time() - Session::get('LAST_ACTIVITY') > 60 ))
      {{Session::forget('name')}}
  @else
     {{Session::get('name')}}
  @endif
So, That's it for today. It was a very interesting and important session indeed. Hope you gonna like it. So stay connected with my blog till the next Tutorial.

Thank you!































Related Articles

0 comments:

Post a Comment