Use MySQL to start PHP session _php Tips

Source: Internet
Author: User
Tags php session php mysql sessions vars
By default, PHP sessions (session) are saved by a file. There are several disadvantages to doing this:

Session files are generally small, but there are a lot of files, and saving many of these small files in a file system is a waste of space and inefficient.
Distributed sites have difficulty using session files to share sessions.
Session file mode is not conducive to the statistics of online users of the session information.
To solve the above problems, we can consider using a database to save session information.

For PHP development, saving sessions with MySQL is a very good choice. MySQL provides an in-memory table type HEAP, which can be considered for further optimization of performance if the amount of data per session is small. However, a table with a Heap type has many limitations, such as that it does not support fields of type text, so it is appropriate to choose MyISAM if the length of the session data is not predictable, and this type of table has no processing overhead and can achieve optimal performance for disk-based tables.

The following is the structure of the sessions table:

DROP TABLE IF EXISTS ' sessions ';
CREATE TABLE ' Sessions ' (
' session_id ' varchar not NULL default ',
' user_id ' int (a) unsigned not NULL default ' 0 ',
' Data_value ' text not NULL,
' Last_visit ' timestamp not NULL,
PRIMARY KEY (' session_id '),
KEY ' user_id ' (' user_id ')
) Type=myisam;
PHP supports the user session module, which allows you to set up custom session-handling functions by Session_set_save_handler. Because the default processing module is files, you should use Session_module_name (' user ') to tell PHP to use the user session module before setting the session handler function with Session_set_save_handler, and Session_ Set_save_handler must be executed before session_start.

After the user session data is serialized in the session processing function, you can deserialize one of the session variables by deserializing it by default PHP serialization, which can be deserialized using the Session::unserialize function.

The following code defines a class that uses MySQL to process PHP sessions, with class_mysql.php in the super simple but super practical PHP MySQL class.

〈?php
/**
* @author Ma Bingyao
* @copyright (C) coolcode.cn
*/

Require_once ("class_mysql.php");

Class Session {
var $db;
Function session (& $DB) {
$this-〉db = & $db;
Session_module_name (' user ');
Session_set_save_handler (
Array (& $this, ' Open '),
Array (& $this, ' Close '),
Array (& $this, ' read '),
Array (& $this, ' write '),
Array (& $this, ' Destroy '),
Array (& $this, ' GC ')
);
Session_Start ();
}
function unserialize ($data _value) {
$vars = Preg_split (
'/([a-za-z_\x7f-\xff][a-za-z0-9_\x7f-\xff]*) \|/',
$data _value,-1, Preg_split_no_empty |
Preg_split_delim_capture
);
for ($i = 0; $vars [$i]; $i + +) {
$result [$vars [$i + +]] = Unserialize ($vars [$i]);
}
return $result;
}
function open ($path, $name) {
return true;
}
function Close () {
return true;
}
function read ($session _id) {
$session _id = $this-〉db-〉escape_string ($session _id);
if ($row = $this-〉db-〉query ("SELECT * from ' Sessions ' where ' session_id ' = ' $session _id ' limit 1")) {
return $row [' Data_value '];
}
else {
$this-〉db-〉query ("INSERT INTO ' sessions ' set ' session_id ' = ' $session _id '");
Return "";
}
}
function Write ($session _id, $data _value) {
$data = $this-〉unserialize ($data _value);
$session _id = $this-〉db-〉escape_string ($session _id);
$data _value = $this-〉db-〉escape_string ($data _value);
$this-〉db-〉query ("Update ' Sessions ' Set")
. "' user_id ' = ' {$data [' user_id ']} ',"
. "' data_value ' = ' $data _value ',"
. "' last_visit ' = null"
. "Where ' session_id ' = ' $session _id '");
return true;
}
function Destroy ($session _id) {
$session _id = $this-〉db-〉escape_string ($session _id);
$this-〉db-〉query ("Delete from ' sessions ' where ' session_id ' = ' $session _id '");
return true;
}
Function GC ($lifetime) {
$this-〉db-〉query ("Delete from ' Sessions ' where Unix_timestamp (now)"-Unix_timestamp (' last_visit ') $lifetime ");
return true;
}
Get Sessions by user_id
function get ($user _id) {
$user _id = $this-〉db-〉escape_string ($user _id);
return $this-〉db-〉query ("SELECT * from ' Sessions ' where ' user_id ' = ' $user _id '");
}
Get Sessions List
function lists ($page, $rows) {
if ($page = = 0) {
return $this-〉db-〉query ("a SELECT * from ' Sessions ' ORDER BY ' user_id '");
}
else {
$start = ($page-1) * $rows;
return $this-〉db-〉query ("the SELECT * from ' Sessions ' ORDER BY ' user_id ' limit $start, $rows");
}
}
}
?〉

The use of this class is very simple, in the original use of Session_Start place, replaced by $session = new Session ($DB) on it. $DB represents the database where the sessions table resides.

In addition, you can use the Get method to obtain all the session information of a user and get a list of all user sessions through the lists method. This makes it easy to manage user sessions.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.