Session Management in PHP – Part3

Storing sessions in a database:

We use the following codes to storing sessions in a database:
<?php

session_set_save_handler(‘_open’,
‘_close’,
‘_read’,
‘_write’,
‘_destroy’,
‘_clean’);

function _open()
{
global $_lms_db;

$db_user = $_SERVER[‘DB_USER’];
$db_pass = $_SERVER[‘DB_PASS’];
$db_host = ‘localhost’;

if ($_sess_db = mysql_connect($db_host, $db_user, $db_pass))
{
return mysql_select_db(‘Clientsessions’, $_lms_db);
}

return FALSE;
}

function _close()
{
global $_lms_db;

return mysql_close($_lms_db);
}

function _read($id)
{
global $_lms_db;

$id = mysql_real_escape_string($id);

$sql = “SELECT data
FROM Clientsessions
WHERE id = ‘$id'”;

if ($result = mysql_query($sql, $_lms_db))
{
if (mysql_num_rows($result))
{
$record = mysql_fetch_assoc($result);

return $record[‘data’];
}
}

return ”;
}

function _write($id, $data)
{
global $_lms_db;

$access = time();

$id = mysql_real_escape_string($id);
$access = mysql_real_escape_string($access);
$data = mysql_real_escape_string($data);

$sql = “REPLACE
INTO Clientsessions
VALUES (‘$id’, ‘$access’, ‘$data’)”;

return mysql_query($sql, $_lms_db);
}

function _destroy($id)
{
global $_lms_db;

$id = mysql_real_escape_string($id);

$sql = “DELETE
FROM Clientsessions
WHERE id = ‘$id'”;

return mysql_query($sql, $_lms_db);
}

function _clean($max)
{
global $_lms_db;

$old = time() – $max;
$old = mysql_real_escape_string($old);

$sql = “DELETE
FROM Clientsessions
WHERE access < ‘$old'”;

return mysql_query($sql, $_lms_db);
}

?>
This requires an existing table named Clientsessions, whose format is as follows:

mysql> DESCRIBE Clientsessions;
+--------+------------------+------+-----+---------+-------+
| Field  | Type             | Null | Key | Default | Extra |
+--------+------------------+------+-----+---------+-------+
| id     | varchar(32)      |      | PRI |         |       |
| access | int(10) unsigned | YES  |     | NULL    |       |
| data   | text             | YES  |     | NULL    |       |
+--------+------------------+------+-----+---------+-------+

This database can be created in MySQL with the following syntax:

CREATE TABLE Clientsessions
(
    id varchar(32) NOT NULL,
    access int(10) unsigned,
    data text,
    PRIMARY KEY (id)
);

Storing our Clientsessions in a database places the trust in the security of your database as well as can keep track of my learning managemen systems client sessions which fulfill a strong requirement.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: