Use the Session_set_save_handler () function in PHP to save the session to the MySQL DB instance _php instance

Source: Internet
Author: User
PHP saves the session by default is the way to save the file, which is only available on Windows with a small amount of space on the file, but if we adopt Uinx or Liux file system, the file space overhead of such file system is very large, However, the session is to be used all the times, a large number of users will create a lot of session files, so that the entire server brings performance problems.

On the other hand, if the server is clustered, it cannot maintain session consistency, so we are ready to use the database to save the session, so that no matter how many servers are used at the same time, Just keep their session on a database server to ensure that the session is complete, how to implement please continue to see.

PHP Save session By default is the use of the file method to save, we can see in the PHP configuration file php.ini this line:
Copy the Code code as follows:
session.save_handler= "Files"

This means that the use of files to save the session, to use the database to save, we need to modify the user mode, change to
Copy the Code code as follows:
Session.save_handler= "Use"

Yes, but it just means that we don't store the session in a file, we also choose the database and the tables that build the database.

To build the database and database table structure, we can use any PHP can be used by the database, because the combination of PHP and MySQL is best, I use MySQL to do the example, of course, according to your needs can be renamed to another database.

Create a database
Copy CodeThe code is as follows:
Create database ' session ';

CREATE TABLE structure
Copy CodeThe code is as follows:
CREATE TABLE ' session ' (ID char (+) NOT NULL, ' user ' char (+), data char (+), primary key (' ID '));

PHP Save session write PHP file
Copy CodeThe code is as follows:
<?php
$con = mysql_connect ("127.0.0.1", "User", "pass");
mysql_select_db ("session");
function open ($save _path, $session _name) {
return (true);
}
function Close () {
return (true);
}
function Read ($id) {
if ($result = mysql_query ("SELECT * from session where id= ' $id '")) {
if ($row = Mysql_felth_row ($result)) {
return $row ["Data"];
}
} else {
Return "";
}
}
function Write ($id, $sess _data) {
if ($result = mysql_query ("Update session set Data= ' $sess _data ' where id= ' $id '")) {
return true;
} else {
return false;
}
}
function Destroy ($id) {
if ($result = mysql_query ("Delete * from session where id= ' $id '")) {
return true;
} else {
return false;
}
}
Function GC ($maxlifetime) {
return true;
}
Session_set_save_handler ("Open", "close", "read", "write", "Destroy", "GC");
Session_Start ();
Proceed to use sessions normally

Save As session_user_start.php.

Now the work of our PHP save session has been completed, as long as you need to use the session, the Session_user_ Start.php is included. Note that this file must be included in the first line of the file, and then be used as if using the file's session.

The above is just a simple tutorial, in the actual application, you can package it more professional, the reference code is as follows:

SessionMysql.class.php
Copy the Code code as follows:
<?php
/**
* Sessionmysql Database Storage class
*/

Defined (' In_qian ') or exit (' Access Denied ');

Class Sessionmysql {

Public $lifetime = 1800; Expiry date, Unit: seconds (s), default 30 minutes
Public $db;
Public $table;

/**
* Constructor function
*/
Public Function __construct () {
$this->db = Base::loadmodel (' Sessionmodel ');
$this->lifetime = base::loadconfig (' System ', ' session_lifetime ');
Session_set_save_handler (
Array (& $this, ' Open '),//execute at Run session_start ()
Array (& $this, ' close '), executed when the script executes or calls Session_write_close () or Session_destroy (), which is executed after all sessions have completed
Array (& $this, ' read '), executed at Run Session_Start (), because at Session_Start, the current session data is read
Array (& $this, ' write '),//This method executes when the script ends and uses session_write_close () to force the session data to be committed
Array (& $this, ' Destroy '),//execute at Run Session_destroy ()
The array (& $this, ' GC ')//execution probabilities are determined by the values of session.gc_probability and session.gc_divisor, and the timing is after Open,read, session_ Start will execute Open,read and GC successively
);
Session_Start (); This is also necessary, open the session, must be executed behind the Session_set_save_handler
}
/**
* Session_set_save_handler Open method
*
* @param $savePath
* @param $sessionName
* @return True
*/
Public function open ($savePath, $sessionName) {
return true;
}
/**
* Session_set_save_handler Close method
*
* @return BOOL
*/
Public function Close () {
return $this-&GT;GC ($this->lifetime);
}
/**
* Read session_id
*
* Session_set_save_handler Read method
* @return String Read session_id
*/
Public function Read ($sessionId) {
$condition = Array (
' WHERE ' = = Array (
' session_id ' = $sessionId
),
' Fields ' = ' data '
);
$row = $this->db->fetchfirst ($condition);
Return $row? $row [' Data ']: ';
}
/**
* Value written to session_id
*
* @param $sessionId Session ID
* @param $data value
* @return Mixed Query execution results
*/
Public function Write ($sessionId, $data) {
$userId = isset ($_session[' UserId ")? $_session[' userId ']: 0;
$roleId = isset ($_session[' Roleid ')? $_session[' Roleid ': 0;
$grouId = isset ($_session[' Grouid ')? $_session[' Grouid ': 0;
$m = defined (' Route_m ')? Route_m: ";
$c = defined (' Route_c ')? Route_c: ";
$a = defined (' Route_a ')? Route_a: ";
if (strlen ($data) > 255) {
$data = ";
}
$ip = Get_ip ();
$sessionData = Array (
' session_id ' = $sessionId,
' user_id ' = $userId,
' IP ' = $ip,
' Last_visit ' = Sys_time,
' role_id ' = $roleId,
' group_id ' = $grouId,
' m ' = $m,
' C ' = $c,
' A ' = $a,
' Data ' = $data,
);
return $this->db->insert ($sessionData, 1, 1);
}
/**
* Delete the specified session_id
*
* @param string $sessionId session ID
* @return BOOL
*/
Public function Destroy ($SESSIONID) {
return $this->db->delete (Array (' session_id ' = $sessionId));
}
/**
* Delete the expired session
*
* @param $lifetime Session expiration date (in seconds)
* @return BOOL
*/
Public Function GC ($LIFETIME) {
$expireTime = sys_time-$lifetime;
return $this->db->delete ("' Last_visit ' < $expireTime");
}
}

Instantiate this class somewhere in the system file!

Copy the Code code as follows:
New Sessionmysql ();

  • Related Article

    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.