Session into Cache (Redis), DB

Source: Internet
Author: User
Tags php session unique id

Why do you want to save the session in the cache

As far as PHP is concerned, the session supported by the language itself is saved to the disk file in a file, saved in the specified folder, the saved path can be set in the configuration file or in the program using function Session_save_path (), but there is a disadvantage,

The first is to save to the file system, inefficient, as long as the usefulness of the session will be from a number of files to find the specified SessionID, inefficient.

The second is that when using more than one server may appear, the session lost problem (in fact, is saved on the other server).

Of course, saving in the cache can solve the above problem, if you use the PHP itself session function, you can use the Session_set_save_handler () function is convenient to the session of the processing process to re-control. If you do not use the PHP session series functions, you can write a similar session function, it is also possible, I am doing this project is this, will be based on the user's mid, login time to hash as SessionID, Each request must add SessionID to be considered legal (when the first login is not required, this time will create SessionID, return to the client), so it is very convenient, concise and efficient. Of course, this article is mainly about the PHP itself in the session "do the Dirty."

Session is saved in the cache

PHP to save the cache to Redis, you can use the configuration file, the session processing and save to make changes, of course, in the program using the Ini_set () function to modify also can, this is very convenient to test, I use this method here, of course, if the production environment is recommended to use the configuration file.

<?phpini_set ( "Session.save_ Handler ", " Session.save_path ", " tcp://localhost:6379 "), Session_Start (), Header (if (isset ($_session[ ' view ']) {$_session[ ' view '] = $_session[ ' view ' + 1;} else{$_session[ ' view ' =  1;} echo       

Here the Session.save_handler is set to Redis,session.save_path as the address and port of Redis, set to refresh later, and then look back at Redis, and you will find the SessionID generated in Redis, SessionID and browser requests are the same,

is not very convenient, only need to change the configuration file can be implemented in Redis to save the session, but I would like to say here is the way to process the session by the program to save to Redis or DB, the next look.

Overwrite the session's handler function with PHP's interface

Here you can first look at the PHP function Session_set_save_handler, php5.4 and then directly implement the Sessionhandlerinterface interface, the code will be more concise. There are several ways to rewrite the main

Open (String $savePath, string $sessionName); Open is similar to a constructor, which is called when a session is started, such as after using the Session_Start () function

Close (); A destructor similar to a class that is called after the write function is called, after which Session_write_close () executes

Read (string $sessionId); Called when the session is read

Write (string $sessionId, string $data); When you save the data, call

Destory ($SESSIONID); When the session is destroyed (Session_destory () or session_regenerate_id ()) calls

GC ($LIFETIME); Garbage cleanup function to clean up outdated obsolete data

Mainly to achieve these methods, according to different storage drivers can set different specific methods, I realized the MySQL database and redis the two save session driver, if necessary, can expand themselves, the extension is very easy.

Here's my Redis implementation (DB and Redis are similar, Redis code is less, post it):

I use the way of the interface, so that it is more convenient to expand, the day I want to use memcached, directly added on the line

<?phpinclude_once __dir__."/interfacesession.php";/** * Save the session in DB */Class RedissessionImplementsinterfacesession{ /*** Save the information of the Session database table*/ Private $_options = Array (  ' Handler ' =Null//Database connection handle  ' Host ' =Null  ' Port ' =Null  ' LifeTime ' =Null); /*** Constructor function*Array of @param $options set information*/ Public function __construct ($options =array ()) {  if (!class_exists ("Redis",False)) {  Die"Redis extensions must be installed"); }  if (!isset ($options [' LifeTime ']) | | $options [' LifeTime '] <=0) {  $options [' lifeTime '] = Ini_get (' Session.gc_maxlifetime '); } $This->_options = Array_merge ($This->_options, $options);} /*** Start the session with the driver*/ Public function begin () {  if ($this->_options[' Host '] = = =null | | $this->_options[' port ' = = = =null | | $this->_options[' lifeTime '] = = =Null ){   ReturnFalse }  //Set Session handler function Session_set_save_handler (  Array ($This' Open '),  Array ($This' Close '),  Array ($This' Read '),  Array ($This' Write '),  Array ($This' Destory '),  Array ($This' GC ') );} /*** Automatically start answering or session_start () the first function that was called after the start of a reply* Similar to the function of constructors*@param $savePath The default save path*@param $sessionName The default parameter name, PHPSESSID*/ Public function open ($savePath, $sessionName) {  if (Is_resource ($this->_options[' Handler ']))ReturnTrue  //Connect to Redis $redisHandle =New Redis (); $redisHandle->connect ($this->_options[' Host ', $this->_options[' Port ']);  if (! $redisHandle) {   ReturnFalse } $this->_options[' handler '] = $redisHandle; $THIS-&GT;GC (NULL);  ReturnTrue} /*** Similar to a destructor, called after write or after the Session_write_close () function*/ Public function Close () {  return $this->_options[' Handler ']->close ();} /*** Read session Information*@param $sessionId uniquely determine the corresponding session data by this ID*@return Session information/empty string*/ Public function Read ($sessionId) {  return $this->_options[' Handler ']->get ($SESSIONID);} /*** Write or modify session data*@param $sessionId The ID of the session to which the data is to be written*@param $sessionData The data to be written, has been serialized*/ Public function Write ($sessionId, $sessionData) {  return $this->_options[' Handler ']->setex ($sessionId, $this->_options[' LifeTime '], $sessionData);} /*** Actively destroying session sessions*@param $sessionId Unique ID of the session to be destroyed*/ Public Function Destory ($sessionId) {  return $this->_options[' Handler ']->delete ($sessionId) >=1? true: false; } /* *   clean up expired data in painting * @param validity * * Public  function gc ($lifeTime) {  // get all SessionID, let the expiration release  $this->_options[' handler ']->keys ("*");   return true; }}              

See Simple Factory mode

Class Session {/** * Driver Handle Save */PrivateStatic$_handler =Null/** * Create session Driver */PublicStaticfunction GetSession($type,$options) { //Single case IfIsset$handler)) { ReturnSelf::$_handler;} Switch ($type) { Case' DB '://Database-driven Session type  Include_once __dir__."/driver/dbsession.php";  $handler =New Dbsession ($options);  Break Case' Redis '://redis driver session type   include_ Once __dir__.  "/driver/redissession.php";    $handler = new Redissession ( $options);   break; default:  return false;   break;}  return self::$_handler =  $handler;}             

Invocation is also very simple,

Session::getsession (' Redis ', Array (        ' host ' + ' localhost ',        ' port ' = ' 6379 '    ),begin (); Session_start();  

Session into Cache (Redis), DB

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.