Home>

Everyday we use sessions to save user login information.Commonly used session saving methods are:file saving (default), database saving, redis saving, memcached, etc. Here mainly records the usage of redis to save sessions when processing sessions with thinkphp.

1.Define in the configuration item:

"session_type" =>"redis", //session save type
"session_prefix" =>"sess_", //session prefix
"redis_host" =>"127.0.0.1" //redis server address
"redis_port" =>6379, //redis connection port number
"session_expire" =>3600, //session expiration time

You can find the method to define the session in the thinkphp/common/functions.php file, and read the session-driven judgment at about 1179 lines.If we define the configuration item session_type, it will create a redis object and call the session storage function session_set_save_handler ().

2. Create redis.class.php file in thinkphp \ library \ think \ session \ driver directory

The contents of the file are as follows:

<?php
namespace think \ session \ driver;
class redis {
//redis connection object
  private $redis;
//session expiration time
  private $expire;
  /**
   * Open method
   * @param type $path
   * @param type $name
   * @return type
   * /
  public function open ($path, $name) {
  $this->expire=c ("session_expire")?c ("session_expire"):ini_get ("session.gc_maxlifetime");
  $this->redis=new redis ();
  return $this->redis->connect (c ("redis_host"), c ("redis_port"));
  }
  /**
   * shut down
   * @return type
   * /
  public function close () {
  return $this->redis->close ();
  }
  /**
   * Read
   * @param string $id
   * @return type
   * /
  public function read ($id) {
  $id=c ("session_prefix"). $id;
  $data=$this->redis->get ($id);
  return $data?$data:"";
  }
  /**
   * Write
   * @param string $id
   * @param type $data
   * @return type
   * /
  public function write ($id, $data) {
  $id=c ("session_prefix"). $id;
  return $this->redis->set ($id, $data, $this->expire);
  }
  /**
   * Destroy
   * @param string $id
   * /
  public function destroy ($id) {
  $id=c ("session_prefix"). $id;
  $this->redis->delete ($id);
  }
  /**
   * Garbage collection
   * @param type $maxlifetime
   * @return boolean
   * /
  public function gc ($maxlifetime) {
  return true;
  }
}

This completes the processing of session by redis.

The method of memcached is almost the same as redis!

php
  • Previous 53 of Manipulating Data in ASPNET 20: Displaying Binary Data in the Data Web Control
  • Next Chapter 47 of Manipulating Data in ASPNET 20: Inserting, Updating, and Deleting Data with the SqlDataSource Control