views:

41

answers:

3

say i store some data associated with a session id in a database . how do i delete the data when the session is timeout in php(i do not want to fill my file sever with all junk data.)?

is there any call back function to call in php ?

+1  A: 

Have the user with the session report back to your database every time he makes a request. (not a new row but update his row so you wont fill your db).

Then have a cronjob or something similar clean up all sessions that have a last report timestamp older than your session timeout value.

Ólafur Waage
what i concern is how to do it after the user close the window(maybe never come back.). is it possible to do?
dannynjust
Then the last report back timer will be old and the cronjob will clean it up.
Ólafur Waage
A: 

I don't know if this qualifies as a callback per se, but maybe you could leverage the destroy handler to remove the stale database information upon explicit session termination?

http://php.net/manual/en/function.session-set-save-handler.php

jtp
that's it , the destroy handler seem what i been looking for . thanks a lot .
dannynjust
You are welcome. How did it work out?
jtp
+1  A: 

You can write php script

<?php
session_start();
$query = "DELETE FROM session_data WHERE session_id = '{$_SESSION['session_id']}'";
// in case you want to read this from ajax as json response
echo mysq_query($query) ? "true" : "false";
session_destroy();
?>

and access this script with ajax on uload event with JQuery

$(window).unload(function() {
    $.get('destroy_session.php', null, function(data, status) {
       // ignore result
    });
});
jcubic
my impression is that it only destroy the session variables , not the data in the database. is that the case?
dannynjust
I add sql stagment
jcubic