PHP implementation Session Storage/deposit Redis

Source: Internet
Author: User

It is not appropriate to use the default session for a site with a large number of visits, we can store it in a database, or use a Redis key-value data storage scheme

Create a new session table first

CREATE TABLE ' Sessions ' (' Sid ' char (+) NOT null, ' updatetime ' int (a) ' is not NULL, ' data ' varchar ($) NOT NULL, UNIQUE KEY ' Sid ' (' Sid ') USING HASH) engine=memory DEFAULT Charset=utf8;

The memory engine of Mysql uses the table, all the data is stored in the memory, the operation speed is fast

<?php//introducing the database file include  "db.php";class mysessionhandler implements  sessionhandlerinterface{    private  $savePath;p rivate  $sessData;p ublic $ expiretime;//set expiration time public  $db;//Database Public function __construct ($hanlder  = ") {$this->db  = database::getinstance ();//Gain Database Strength  ///var_dump ($this->db);}     public function open ($savePath,  $sessionName)     {         return true;    }     public function close ()     {         return true;    }    public function read ($id)     {     $sql  = "Select * from sessions where  sid = ' $id '; $result  =  $this->db->execute ($sql);Empty ($result)) { return  $this->sessdata =  $result;} Parameters of the     }            //function   $id  ->  Current session id            //data  ->  string     public function write after serialization ($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 present 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;}} else{//does not exist then generate generate $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;} &NBSP;&NBSP;&NBSP;&NBSP;}&NBSP;&NBSP;&NBSP;&NBSP;PUBLIC&NBSP;FUNCTION&NBSP;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 of

There are two ways PHP manuals can be used here

1, realize the object of Sessionhandlerinterface excuse, since PHP5.4 can use

2, direct use of Session_set_save_handler

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);//return associative array $ result = Fetch () $rs, return $result;} Public function Execute ($sql) {$rs = self:: $db->exec ($sql); return $rs;}} $data = Database::getinstance ();//var_dump ($data);

Using Redis storage session

<?phpclass SessionManager{private  $redis;p rivate  $sessionSavePath;p rivate  $sessionName; private  $sessionExpireTime  = 30;public function __construct () {$this->redis =  new redis (); $this->redis->connect (' 127.0.0.1 ', 6379);     //connection 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 expiration Time return true;} Return false;} Public function destoRy ($id) {if ($this->redis->delete ($id)) {return true;} Return false;} PUBLIC&NBSP;FUNCTION&NBSP;GC ($maxlifetime) {return true;} destructor Public function __destruct () {session_write_close ();}} $re  = new sessionmanager (); $_session[' name '] =  "QQ"; echo $_session[' name '];


PHP implementation Session Storage/deposit Redis

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.