Saving session in database is best practice for website security. so if we want more security then we need to save session in database.
Here are few steps to save session in database
step 1--> Create a table name as sessionsdata
step 2--> create a function for open database connection
function _open()
{
global $_sess_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('sessions', $_sess_db);
}
return FALSE;
}
step 3--> Function for close connection
function _close()
{
global $_sess_db;
return mysql_close($_sess_db);
}
Step 4--> Function for read session from database
function _read($id)
{
global $_sess_db;
$id = mysql_real_escape_string($id);
$sql = "SELECT data
FROM sessionsdata
WHERE id = '$id'";
if ($result = mysql_query($sql, $_sess_db))
{
if (mysql_num_rows($result))
{
$record = mysql_fetch_assoc($result);
return $record['data'];
}
}
return '';
}
Step 5--> write session data to database
function _write($id, $data)
{
global $_sess_db;
$access = time();
$id = mysql_real_escape_string($id);
$access = mysql_real_escape_string($access);
$data = mysql_real_escape_string($data);
$sql = "REPLACE
INTO sessionsdata
VALUES ('$id', '$access', '$data')";
return mysql_query($sql, $_sess_db);
}
step 6--> Destroy database
function _destroy($id)
{
global $_sess_db;
$id = mysql_real_escape_string($id);
$sql = "DELETE
FROM sessionsdata
WHERE id = '$id'";
return mysql_query($sql, $_sess_db);
}
step 7--> Create a _clean function for remove Garbage data
function _clean($max)
{
global $_sess_db;
$old = time() - $max;
$old = mysql_real_escape_string($old);
$sql = "DELETE
FROM sessionsdata
WHERE access < '$old'";
return mysql_query($sql, $_sess_db);
}
Now call your session handler function
session_set_save_handler('_open',
'_close',
'_read',
'_write',
'_destroy',
'_clean');
2 Comment(s)