Redis replaces php file storage session

Source: Internet
Author: User
: This article describes how to replace the PHP file storage session in redis. For more information about PHP tutorials, see. Before viewing an instance, please first understand the usage of the PHP session_set_save_handler function

Define a SessionManager class
Class SessionManager {
Private $ redis;
Public function _ construct (){
$ This-> redis = new Redis ();
$ This-> redis-> connect ('192. 168.0.102 ', 192 );
$ Retval = session_set_save_handler (
Array ($ this, "open "),
Array ($ this, "close "),
Array ($ this, "read "),
Array ($ this, "write "),
Array ($ this, "destroy "),
Array ($ this, "gc ")
);
Session_start ();
}
Public function open ($ path, $ name ){
Return true;
}
Public function close (){
Return true;
}
Public function read ($ id ){
$ Session_value = $ this-> redis-> get ($ id );
If ($ session_value ){
Return $ session_value;
} Else {
Return "";
}
}
Public function write ($ id, $ data ){
If ($ this-> redis-> set ($ id, $ data )){
Return true;
} Else {
Return false;
}
}
Public function destroy ($ id ){
If ($ this-> redis-> delete ($ id )){
Return true;
} Else {
Return false;
}
}
Public function gc ($ maxlifetime ){
Return true;
}
Public function _ destruct (){
Session_write_close ();
}
}

The code for creating a session_set.php is as follows:

Include ("SessionManager. php ");
New SessionManager ();
$ _ SESSION ['User _ name'] = "xxdcsnd@sina.com ";

The code for creating a session_set.php is as follows:

Include ("SessionManager. php ");
New SessionManager ();
Echo $ _ SESSION ['User _ name'];

Test output result xxdcsnd@sina.com

Note: php. ini session. save-hadler is set to user, otherwise session_set_save_handler will not take effect

The above introduces the replacement of PHP file storage session in redis, including the content, hope to be helpful to friends interested in PHP tutorials.

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.