How can i store sessions in database ? I did it using this code :
function write ($session_id, $session_data)
// write session data to the database.
{
if (!empty($this->fieldarray)) {
if ($this->fieldarray['session_id'] != $session_id) {
// user is starting a new session with previous data
$this->fieldarray = array();
} // if
} // if
if (empty($this->fieldarray)) {
// create new record
$array['session_id'] = $session_id;
$array['date_created'] = getTimeStamp();
$array['last_updated'] = getTimeStamp();
$array['session_data'] = addslashes($session_data);
$this->_dml_insertRecord($array);
} else {
// update existing record
if (isset($_SESSION['logon_user_id'])) {
$array['user_id'] = $_SESSION['logon_user_id'];
} // if
$array['last_updated'] = getTimeStamp();
$array['session_data'] = addslashes($session_data);
$this->_dml_updateRecord($array, $this->fieldarray);
} // if
return TRUE;
} // write
But how should i remove it automaticaly like before. I mean how to delete sessions after time out automatically?
I had to deal with this along time ago, and there are 2 solutions, neither of which are pretty, but here it goes.
In the order of events (loosely), your script will check to see if there was a session ID sent to the server, then it will see if that session is in your database, and if the the session has expired. As soon as you've established the connection to your session db, you might consider running a DELETE query on all records with an expiration date past the current time stamp. Then search for the ID that the user just sent. This way clean up is being performed every time people use your site
The next way, which you might consider doing in addition, is to have a CHRON Job or other automated script which runs every so often to clean expired entries from your session table. This is a good method if your site receives light and infrequent traffic.
A combination of methods is this. With in your script when you are validating your session, check the expire date when the session data is found. if the ID is found, but the session is expired, delete the session and start a new one. If you do it this way, you won't have to run into too many problems of ID collision or lots of queries slowing down your server. You can still run your chron job at the end each day to run a complete cleanup.
Make sure if your system has a logout button of some type that the act of manually logging out will trigger the deletion of the user session.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With