perkiset

I've shied away from using sessions with

PHP

  because I did not like the file model.

Additionally, I do not like standard sessions because garbage collection is done at the start of a surfer's pull. What I mean is this: there is no cron job or anything that gets rid of old sessions. Whenever a page is pulled, the sessions system unlinks (deletes) all files older than (the TTL) - this is really a problem on high volume sites, because at any given moment you might have a bunch of sessions that need to get eliminated and the delivery of (this current page) to the surfer is now delayed while that garbage collection is executed.

So I've used either APC to store serialized arrays for state or a database for a more stable and scalable solution. But I wanted to get back to a more normalized form of

PHP

 , so I started using the $_SESSION variable and created my own storage functions.

I am MASSIVELY embarrassed to say that it is beyond trivial and I had nothing to worry about.

This little snippet is my current sessions alternate storage code. The most important part to note, is that the garbage collection function does absolutely nothing. That's because I do garbage collection via a cron job and take the burden of that job out of band.

I'll probably do an APC version of this later, but garbage collection is more tricky, so we'll save that for another day.

Note that this system expects and requires that a dbConnection object was created and stored in the GLOBALS array as 'utilDB' - that's one of the things that make it go fast. The table to storing sessions can be created with this:

CREATE TABLE `sessions` (
  `id` varchar(64) NOT NULL,
  `lasttouch` datetime NOT NULL,
  `data` text NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
[/pre]
Enjoy!
/p


<?

php

 

session_set_save_handler("_session_open","_session_close","_session_read","_session_write","_session_destroy","_session_garbage_collection");
session_start();


function _session_open($path,$name) { return true; }
function _session_close() { return true; }
function _session_garbage_collection($maxlife) { return true; }
function _session_read($id) { return $GLOBALS['utilDB']->singleAnswer("select data from sessions where id='$id'"); }
function _session_destroy($id) { return $GLOBALS['utilDB']->query("delete from sessions where id='$id'"); }
function _session_write($id, $data)
{
$data = mysql_escape_string($data);
$now = date('Y-m-d H:i:s', time());
return $GLOBALS['utilDB']->query("replace into sessions(id, data, entity, application, lasttouch) values('$id', '$data', '$now')");
}
?>


Perkiset's Place Home   Politics @ Perkiset's