On 5/10/06, Martijn Grendelman <martijn@xxxxxxxxxxxxxx> wrote:
Hi,
> i don't understand the need though for session persistence like this;
> i'd expect a centralized session manager (msession for instance) or
> just using a central database for the information would suffice.
> that's how i've been doing it, not sure why everyone has all these
> unique requirements to make sure they can persist sessions across IP
> addresses and AOL proxies and such.
A centralized session manager would be nice, but I for one haven't been
able to find a decent solution for use with PHP. I don't know about
other systems or APIs.
It's very simple to make your own which uses only a single database
table in mysql. I used to use msession, but it had some overhead it
seemed like, and a database-driven one was less "thick" - the other
good thing about writing your own session handler is that you can call
other things on session start or close, etc.
I'd suggest using that (a mysql one)
I'll try giving you mine though, also:
### SQL:
CREATE TABLE `session` (
`ID` varchar(32) character set utf8 NOT NULL default '',
`uid` int(10) unsigned NOT NULL default '0',
`data` mediumtext character set utf8 NOT NULL,
`accessed` int(10) unsigned NOT NULL default '0',
PRIMARY KEY (`ID`),
KEY `accessed` (`accessed`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8
### cron script (run it every so often, i have it set to 5 minutes -
otherwise there is no garbage collection - it will remove sessions
that are over 1800 seconds old.
$expiry = time() - 1800;
db_query("DELETE FROM session WHERE accessed < $expiry");
### the session PHP functions
function session_close() {
return true;
}
function session_die($id) {
db_query("DELETE FROM session WHERE ID='$id'");
return true;
}
function session_gc($maxlifetime) {
return true;
}
function session_open($path,$name) {
return true;
}
function session_read($id) {
$dchk = db_query("SELECT data FROM session WHERE ID='$id'");
if(db_numrows($dchk) == 1) {
if(!isset($_SESSION['row'])) { $_SESSION['row'] = 1; }
list($data) = db_rows($dchk);
return base64_decode($data);
} else {
return "";
}
db_free($dchk);
return true;
}
function session_write($id,$data) {
$data = base64_encode($data);
if(!isset($_SESSION['row'])) {
db_query("INSERT IGNORE INTO session
(ID,data,accessed) VALUES('$id','$data',UNIX_TIMESTAMP(NOW()))");
} else {
db_query("UPDATE session SET
data='$data',accessed=UNIX_TIMESTAMP(NOW()) WHERE ID='$id'");
}
return true;
}
### configuration in each script (common include)
ini_set("session.use_only_cookies","1");
ini_set("session.gc_probability","0");
ini_set("session.cookie_domain","yourdomain.com");
session_set_save_handler("session_open", "session_close",
"session_read", "session_write", "session_die", "session_gc");
session_start();
register_shutdown_function('session_write_close')
all that seems to work well for me...
|