tags:

views:

86

answers:

2

I need to perform an action after a session times out. However I have no clue how to trigger that action without an incoming request. An event handler/a listener/a timer would suit perfect but since PHP does not support such a thing it is really difficult to accomplish what I want.

After lot of searching I bumped into session_set_save_handler but I still cannot fully understand how this method works. If I write code that triggers the action inside the close method when it will be executed?

I also need to keep the current session solution as it is and I wonder what the ramifications of using session_set_save_handler in conjunction with that will be? (My current solution sets a session cookie, assigns a name to the session and starts the session, when the user logs out or a request is done after the session timeout (that value is set in a configuration file) the session is completely destroyed)

Regards!

A: 

PHP needs to run in some way for PHP code to execute. Either through a user request or a cronjob.

A Session is saved to the locale storage when a PHP request finishes executing or when session_write_close() is called

This session_set_save_handler() allows you to write your own save handler.

Ólafur Waage
<quote>This session_set_save_handler() allows you to write your own save handler.</quote>You mean like storing the session key in a database and delete it on session destroy?
lotbsis
A: 

This is somewhat difficult to do in php, AFAIK.

But you can try by making a passive session handler:

  • Store session ids associated with a timestamp.
  • Each time the user associated with certain id makes a request, refresh it's timestamp.

You can detect defunct sessions by comparing the system's current, and each session id's timestamps. The ones that differ above a given treshold (say 30min), are assumed to have passed away. Then you can execute your own save handlers for these session ids.

This won't work if the session end handler needs to be executed inmediately, as this process is executed each time when a request arrives (from any user), so it will depend directly on the website's traffic flow.

But you can also solve it by setting cron jobs each 15min or so. Depending on how expensive your save handlers are, seems an acceptable periodicity.

azkotoki
<quote>You can detect defunct sessions by comparing the system's current, and each session id's timestamps. The ones that differ above a given treshold (say 30min), are assumed to have passed away. Then you can execute your own save handlers for these session ids.</quote>But this requires a request to be made, right? It cant be done automatically. Correct?
lotbsis
Yes, the only way to do it seems by setting cron jobs or something of the like. You can't get any php code executed outside a request (except with cron jobs).
azkotoki