<?php
ini_set("session.gc_probability", 100); // "Собираем мусор" при каждом
// обращении к функциям обработки сессий
// database connection info:
define('DB_SERVER', 'localhost');
define('DB_DATABASE', 'session_data');
define('DB_USER', 'session');
define('DB_PASS', '');
class SessionHandler
{
function sess_open($save_path, $session_name)
{
// ignore the PHP values for path & name
// allocate a database connection:
global $SESSION_DB_RESOURCE; // note: can't use a member variable because the
// methods are called statically
$SESSION_DB_RESOURCE = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die("Can't connect to DB");
mysql_select_db(DB_DATABASE, $SESSION_DB_RESOURCE) or die("Can't select database");
return true;
}
function sess_close()
{
global $SESSION_DB_RESOURCE;
if (is_resource($SESSION_DB_RESOURCE))
{
return mysql_close($SESSION_DB_RESOURCE);
}
else
{
return true;
}
}
function sess_read($id)
{
global $SESSION_DB_RESOURCE;
// get session data:
$sql = "
SELECT
session_data
FROM
sessions
WHERE
session_key = '$id'
AND
valid = 'yes'
";
$query = mysql_query($sql, $SESSION_DB_RESOURCE) or die("Query failed");
$row = mysql_fetch_row($query);
return $row[0];
}
function sess_write($id, $sess_data)
{
global $SESSION_DB_RESOURCE;
$sql = "
SELECT
session_id
FROM
sessions
WHERE
session_key = '$id'
AND
valid = 'yes'
";
$query = mysql_query($sql, $SESSION_DB_RESOURCE) or die("Query failed");
if (mysql_num_rows($query))
{
// session exists: update
$row = mysql_fetch_row($query) or die("Can't fetch row");
$session_id = $row[0];
$sql = "
UPDATE
sessions
SET
session_data = '". mysql_escape_string($sess_data) ."',
create_ts = now()
WHERE
session_id = $session_id
";
}
else
{
// session does not exist: insert
$sql = "
INSERT
INTO
sessions
(
create_ts,
valid,
session_key,
session_data
)
VALUES
(
now(),
'yes',
'". mysql_escape_string($id) ."',
'". mysql_escape_string($sess_data) ."'
)
";
}
$writeQ = mysql_query($sql, $SESSION_DB_RESOURCE) or die("Write query failed");
return true;
}
function sess_destroy($id)
{
global $SESSION_DB_RESOURCE;
$sql = "
UPDATE
sessions
SET
valid = 'no'
WHERE
session_key = '$id'
";
$destroyQ = mysql_query($sql, $SESSION_DB_RESOURCE) or die("Destroy query failed");
return true;
}
function sess_gc($maxlifetime)
{
global $SESSION_DB_RESOURCE;
// invalidate any sessions older than $maxlifetime seconds old
$sql = "
UPDATE
sessions
SET
valid = 'no'
WHERE
valid = 'yes'
AND
create_ts < DATE_ADD(now(), INTERVAL -$maxlifetime SECOND)
";
$gcQ = mysql_query($sql, $SESSION_DB_RESOURCE) or die("Garbage collection query failed");
return true;
}
}
session_set_save_handler(
array("SessionHandler", "sess_open"),
array("SessionHandler", "sess_close"),
array("SessionHandler", "sess_read"),
array("SessionHandler", "sess_write"),
array("SessionHandler", "sess_destroy"),
array("SessionHandler", "sess_gc")
) or die("Failed to register session handler");
?>