-3

I have a usecase that i want to check if the session is going to expire in 30 sec or 60 sec. if so I should be able to extend the session. I am fine with any solutions with session or cookies. How do I acomplish that. Pls eloborate your solution. But I should know before the session expires.

indianwebdevil
  • 4,879
  • 7
  • 37
  • 51

1 Answers1

0

php.ini sets a sesion_maxlifetime but this is not reliable because a session could last longer, depending on when the garbage collector in PHP is called.

I recommend storing your session metadata in a database with a column to specify the expiry time (you could use datetime quite well). Once a user calls a page with session_start(), you can take the $_COOKIE['my_cookie_name] value and use a library like mysqli to fetch the expiry time. You may want to then store this as a session variable too, as well as in the database, so you don't have to make database calls all the time to get the session expiry, e.g. $_SESSION['expiry'] = time() + 60*60*24*365 for a session that'll expire in 356 days.

You can then do a session_unset() with a session_destroy() function call to clean your session when validating the user request.

Actual session data can also be stored in a database but you should consider using a key-value store like Redis to make this smoother: doing a lot of database calls on volatile data like sessions might not be the best practice and could create unnecessary load on your servers, especially with many users.

ABC Taylor
  • 70
  • 8