I have a web app that stores some objects in the user session so it doesn’t have to keep calling to the database every time there’s an AJAX hit to the server.
I want to write some cleanup/save functions that are triggered when the user closes the browser tab or navigates away from the page.
Is the session “destroyed” (i.e. calls __destruct for any objects it contains) if a user navigates away from the page – or is it better to handle this client side with a javascript that sends an AJAX request when the user navigates away?
The session is in PHP is not defined as a class. Instead, we have a set of session functions to manipulate the session. To make sure that you have destroyed the session, you need to explicitly call :
If you have not destroyed the session, the session will do garbage collection after the session timeout. The garbage collection depends on the following parameters – session.gc_maxlifetime, session.gc_divisor and session.gc_probability. To make sure that the garbage collection runs on every session, you will have to add session.gc_probability to 100%. But it definitely add an overhead to the server, especially if yours is a high traffic server.
If you do not explicitly keep track of the sessions and destroy it after use, you are leaving some part of the session management to the OS. See the note from PHP.net:
The best way is to send a flag via Ajax call when the browser or tab is closed. You can detect it via : window.onunload event of javascript.