note 64101 deleted from ref.session by bjori
| From: | bjori@php.net | Date: | Fri, 07 Apr 2006 14:56:09 +0000 |
| Subject: | note 64101 deleted from ref.session by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-107520@lists.php.net to get a copy of this message | ||
Note Submitter: kakugo at kakugo dot com
Reason: in docs
----
A useful and more managable session code would be to use an SQL database to store the session data,
obviously this gives you more control over the creation and use of the sessions.
Example:
<?
$expire_time = "1800";
// makes it easier for the other functions..
function db_data ($table, $field, $field_1, $where)
{
if (mysql_num_rows (mysql_query ("SELECT
$field FROM $table WHERE
$field_1 = '$where'")) != 0)
{
$result = mysql_result (mysql_query ("SELECT $field FROM $table
WHERE $field_1 = '$where'"), 0);
return $result;
}
else
{
return false;
}
}
// create session given $user_id, -1 for anonymous
function create_session ($user_id)
{
$session_id = md5 (uniqid ($_SERVER['REMOTE_ADDR']).time());
setcookie ("site_session", $session_id, $expire_time + time(), "/");
mysql_query ("DELETE FROM user_sessions WHERE '$expire_time' +
session_active <= '".time()."' || user_id =
'$user_id' && user_id != '-1' || user_id =
'-1' && user_ip = '$user_ip'");
mysql_query ("INSERT INTO user_plops VALUES ('$session_id',
'$user_id', '$_SERVER['REMOTE_ADDR']',
'".time()."')");
return $session_id;
}
// $user_id is retreived with a login function:
if (isset ($_POST['site_login']) && isset ($_POST['user_name'])
&& isset ($_POST['user_pass']))
{
if (db_data ("users", "user_pass", "user_name",
$_POST['user_name']) == $_POST['user_pass'])
{
$user_id = db_data ("users", "user_id", "user_name",
$_POST['user_name']);
create_session ($user_id);
}
}
// then you can retreive the data on every page load:
function session_data ($session_id)
{
mysql_query ("DELETE FROM user_sessions WHERE '$expire_time' +
session_active <= '".time()."'");
if (db_data ("user_sessions", "user_ip", "session_id", $session_id)
&& db_data ("user_sessions", "user_ip", "session_id",
$session_id) == $_SERVER['REMOTE_ADDR'])
{
mysql_query ("UPDATE user_sessions SET session_active =
'".time()."' WHERE session_id = '$session_id'");
setcookie ("site_session", $session_id, $expire_time + time(), "/");
$user_id = db_data ("user_sessions", "user_id", "session_id",
$session_id);
$user_data = mysql_fetch_array (mysql_query ("SELECT * FROM users WHERE
user_id = '$user_id'"));
return $user_data;
}
else
{
if (isset ($_COOKIE["site_session"]))
{
setcookie ("site_session", "", 0, "/");
}
}
}
?>
if you want an anonymous login you can just preset the $user_id to -1 when the page loads if no
$user_id is defined, creating a user with that id in the users table.