Start a PHP session using MySQL

Source: Internet
Author: User
Tags php session
By default, PHP sessions are saved through files. This has the following disadvantages:

Session files are usually very small, but there are many files. it is a waste of space to save many such small files in the file system, and the efficiency is not high.
Distributed websites cannot use session files to share sessions.
The session file method is not conducive to collecting the session information of online users.
To solve the preceding problems, we can use a database to store session information.

For PHP Development, saving sessions using MySQL is a very good choice. MySQL provides a table type Heap established in the memory. if the data volume of each session is small, you can use this type of table to further optimize the performance. However, a Heap table has many restrictions. for example, it does not support text fields. Therefore, it is more appropriate to select MyISAM if the session data record length cannot be predicted, this type of table has no transaction processing overhead, and provides optimal performance for disk-based tables.

The structure of the sessions table is as follows:

Drop table if exists 'session ';
Create table 'Session '(
'Session _ id' varchar (32) not null default '',
'User _ id' int (10) unsigned not null default '0 ',
'Data _ value' text not null,
'Last _ visit' timestamp (14) not null,
Primary key ('session _ id '),
KEY 'user _ id' ('User _ id ')
) TYPE = MyISAM;
PHP supports the user session module. you can use session_set_save_handler to set custom session handler functions. Because the default processing module is files, before using session_set_save_handler to set the session processing function, use session_module_name ('user') to tell PHP to use the user session module, session_set_save_handler must be executed before session_start.

User session data is serialized in session processing functions. to retrieve a session variable, you can deserialize It. the default value is php Serialization. you can use session :: unserialize function to deserialize.

The following code defines a class that uses MySQL to process PHP sessions. for details about class_mysql.php, see "super simple but super practical mysql class of PHP".

<〈? Php
/**
* @ Author Ma Bingyao
* @ Copyright (C) 2005 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, 'deststroy '),
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 'session' where 'session _ id' = '$ session_id 'limit 1") {
Return $ row ['data _ value'];
}
Else {
$ This-> db-> query ("insert into 'session' 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 'session' 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 'session' where 'session _ id' = '$ session_id'");
Return true;
}
Function gc ($ lifetime ){
$ This-> db-> query ("delete from 'session' 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 'session' where 'user _ id' = '$ user_id'");
}
// Get sessions list
Function lists ($ page, $ rows ){
If ($ page = 0 ){
Return $ this-> db-> query ("select * from 'session' order by 'user _ id'");
}
Else {
$ Start = ($ page-1) * $ rows;
Return $ this-> db-> query ("select * from 'session' order by 'user _ id' limit $ start, $ rows");
}
}
}
? > 〉

This class is easy to use. replace session_start with $ session = new session ($ db. $ Db indicates the database where the sessions table is located.

In addition, you can use the get method to obtain all session information of a user and use the lists method to obtain the list of all user sessions. In this way, you can easily 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.