Php implements Session storage to Redis

Source: Internet
Author: User
This article mainly introduces how to store Session in Redis in php. phpSession can be saved to text, memory, and database. This article describes how to store Session in Redis, it is not suitable for websites with large traffic volumes to use the default Session. we can store the Session in the database or use the Redis KEY-VALUE data storage solution.
First, create a session table.

CREATE TABLE `sessions` ( `sid` char(40) NOT NULL, `updatetime` int(20) NOT NULL, `data` varchar(200) NOT NULL, UNIQUE KEY `sid` (`sid`) USING HASH) ENGINE=MEMORY DEFAULT CHARSET=utf8;

The memory engine of Mysql uses memory tables. all data is stored in the memory and the operation speed is fast.

<? Php // introduce the database file include "db. php "; class MySessionHandler implements SessionHandlerInterface {private $ savePath; private $ sessData; public $ expiretime; // Set the Expiration Time to public $ db; // Database public function _ construct ($ hanlder = '') {$ this-> db = Database: getInstance (); // Obtain database strength // var_dump ($ this-> db);} public function open ($ savePath, $ sessionName) {return true;} public function close () {return true;} public f Unction read ($ id) {$ SQL = "select * from sessions where sid = '$ ID'"; $ result = $ this-> db-> execute ($ SQL ); if (! Empty ($ result) {return $ this-> sessData = $ result ;}} // function parameter $ id-> Current session ID // DATA data-> serialized string public function write ($ id, $ DATA) {// echo $ id; // echo $ data; $ now = time (); $ newExp = $ now + $ this-> expiretime; // total time = current time + term Time $ SQL = "select * from sessions where sid = '$ ID '"; $ result = $ this-> db-> getOne ($ SQL); // var_dump ($ result); if ($ data = ''| isset ($ data )) {$ data = $ this-> sessData;} if ($ result) {// if yes, update $ SQL = "update sessions set updatetime = '$ newExp ', data = '$ data' where sid =' $ ID' "; // echo $ SQL; $ update_data = $ this-> db-> execute ($ SQL ); if ($ update_data) {return true ;}} if else {// does not exist, $ SQL = "insert into sessions (sid, updatetime, data) values ('$ ID ', '$ now', '$ data') "; $ insert_data = $ this-> db-> execute ($ SQL); if ($ insert_data) {return true ;}} return false;} public function destroy ($ id) {// destroy $ SQL = "delete from sessions where sid = ". "$ id"; $ destory = $ this-> db-> execute ($ SQL); if ($ destory) {return true;} else {return false ;}} public function gc ($ sessMaxLifeTime) {$ t = time (); $ SQL = "delete from sessions where $ t-'updatetime' >$ {sessMaxLifeTime }"; $ data = $ this-> db-> execute ($ this-> tosql); if ($ data) {return true;} else {return false;} return true ;}}

Instantiation

The PHP manual can be used in either of the following ways:
1. implement the SessionHandlerInterface object. it can be used from PHP5.4.
2. directly use session_set_save_handler

// Determine the PHP version if (version_compare (PHP_VERSION, 5.4) = 1) {session_set_save_handler ($ handler, true); session_start ();} else {ini_set ('session. use_trans_sid ', 0); ini_set ('session. use_cookies ', 1); ini_set ('session. cookie_path ','/'); ini_set ('session. save_handler ', 'User'); session_module_name ('user'); session_set_save_handler (array ($ session, "open"), array ($ session, "close "), array ($ session, "read"), array ($ session, "write"), array ($ session, "destory"), array ($ session, "gc"); session_start () ;}$ _ SESSION ['QQ'] = "QQ"; echo $ _ SESSION ['QQ'];

Database code

<? Php class Database {static $ instance; static $ db; static function getInstance () {if (self ::$ instance) {return self ::$ instance ;} else {return new Database () ;}} public function _ construct () {self: $ db = new PDO ('MySQL: host = localhost; dbname = session ', 'root', '');} public function getOne ($ SQL) {$ rs = self: $ db-> query ($ SQL ); @ $ rs-> setFetchMode (PDO: FETCH_ASSOC); // returns the joined array $ result = $ rs-> fetch (); return $ result ;} public function execute ($ SQL) {$ rs = self: $ db-> exec ($ SQL); return $ rs ;}// $ data = Database :: getInstance (); // var_dump ($ data );

Use REDIS to store Sessions

<? Phpclass SessionManager {private $ redis; private $ sessionSavePath; private $ sessionName; private $ sessionExpireTime = 30; public function _ construct () {$ this-> redis = new Redis (); $ this-> redis-> connect ('2017. 127. 0.0.1 ', 6379); // Connect to redis $ retval = session_set_save_handler (array ($ this, "open"), array ($ this, "close"), array ($ this, "read"), array ($ this, "write"), array ($ this, "destory"), array ($ this, "gc ")); session_start ();} public function open ($ path, $ name) {return true;} public function close () {return true;} public function read ($ id) {$ value = $ this-> redis-> get ($ id); if ($ value) {return $ value;} else {return "";}} public function write ($ id, $ data) {if ($ this-> redis-> set ($ id, $ data )) {$ this-> redis-> expire ($ id, $ this-> sessionExpireTime); // Set the expiration time to return true;} return false;} public function destory ($ id) {if ($ this-> redis-> delete ($ id) {return true;} return false;} public function gc ($ maxlifetime) {return true ;} // destructor public function _ destruct () {session_write_close () ;}}$ re = new SessionManager (); $ _ SESSION ['name'] = "qq "; echo $ _ SESSION ['name'];

The above is a detailed description of the php method for storing Session data in Redis. I hope it will be helpful for your learning.

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.