Use the Session_set_save_handler () function to save the session to the MySQL database

Source: Internet
Author: User
Tags session id php and mysql sessions

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 way to save the file, we in the PHP configuration file php.ini can see such a line,

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

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

CREATE database ' session ';

CREATE TABLE structure

CREATE TABLE ' session ' (ID char (+) NOT NULL, ' user ' char (+), data char (+), primary key (' ID '));

PHP Save session Write PHP file

<?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 fals e;}} 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 included in. Note that this file must be included in the first line of the file , And then it's just like using a file's session as a way to use it.

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

<?php/** * Sessionmysql Database storage class */defined (' In_qian ') or exit (' Access Denied '); class Sessionmysql {public $lifetime = 180 0; Validity period, unit: seconds (s), default 30 minutes public $db;p ublic $table;/** * constructor */public function __construct () {$this->db = Base::loadmodel ( ' Sessionmodel '); $this->lifetime = base::loadconfig (' System ', ' session_lifetime '); Session_set_save_handler ( Array (& $this, ' Open '),//execute Array (& $this, ' Close ') when running Session_Start (),//In script execution complete or call Session_write_close () or Session_destroy () is executed, that is, after all sessions are executed, the array (& $this, ' read '),//is executed when Session_Start () is run, because at Session_Start, is going to read the current session data array (& $this, ' write '),//This method executes the array (& $this, when the script ends and uses session_write_close () to force the session data to be committed ' Destroy '),//execute Array (& $this, ' GC ') when running Session_destroy ()//execution probability is determined by session.gc_probability and Session.gc_divisor values , the timing is after Open,read, Session_Start will be executed successively Open,read and GC); Session_Start (); This is also necessary, open session, must be executed behind 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 ']: ';} /** * Write session_id value * * @param $sessionId session ID * @param $data value * @return mixed query execution result */public function write ($sess Ionid, $data) {$userId = Isset ($_session[' userid '])? $_session[' userid ']: 0; $roleId = isset ($_session[' Roleid '))? $_ses sion[' 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 Expired session * * @param $lifetime session expiration (in seconds) * @return Bool*/public function gc ($lifetime) {$expireTime = SYS _time-$lifetime; return $this->db->delete ("' Last_visit ' < $expireTime");}}? >

In the system file somewhere, instantiate this class can!!!

new Sessionmysql ();

Read more: How does PHP Save the session to memcached?

Use the Session_set_save_handler () function to save the session to the MySQL database

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.