session is saved to an MySQL database instance using the session_set_save_handler of function in php

  • 2021-07-24 10:32:38
  • OfStack

PHP Save session is saved by default as a file, This can only be used on windows where the file space overhead is very small. However, if we use the file system on uinx or liux, the file space overhead of such a file system is very large. However, session needs to be used all the time, and a large number of users have to create a lot of session files, which brings performance problems to the whole server.

On the other hand, if the server is clustered, it can't keep the uniformity of session, so we are ready to use the database to save session, so that no matter how many servers are used at the same time, as long as their session is saved on a database server, it can ensure the integrity of session. Please continue to see how to realize it.

PHP Save session is saved in the file mode by default. We can see this line in the configuration file PHP. ini of PHP:


session.save_handler="files"

This means to use files to save session. If you want to use databases to save it, we need to modify it into user mode and change it to

session.save_handler="use"

That's OK, but this just means that we don't store session in a file way, and we have to choose the database and build the table of the database.

To establish the database and the table structure of the database, we can use any database that PHP can use, because the combination of PHP and mysql is the best, I will use mysql as an example, of course, according to your needs can be renamed another database.

Create a database


create database 'session';

Create a table structure

create table 'session'( id char(32) not null , 'user 'char(30), data char(3000) ,primary key ('id') );

PHP Save session Write PHP File

<?php
$con = mysql_connect("127.0.0.1", "user" , "pass");
mysql_select_db("session");
function open($save_path, $session_name) {
 return(true);
}
function close() {
 return(true);
}
function read($id) {
 if ($result = mysql_query("select * from session where id='$id'")) {
  if ($row = mysql_felth_row($result)) {
   return $row["data"];
  }
 } else {
  return "";
 }
}
function write($id, $sess_data) {
 if ($result = mysql_query("update session set data='$sess_data' where id='$id'")) {
  return true;
 } else {
  return false;
 }
}
function destroy($id) {
 if ($result = mysql_query("delete * from session where id='$id'")) {
  return true;
 } else {
  return false;
 }
}
function gc($maxlifetime) {
 return true;
}
session_set_save_handler("open", "close", "read", "write", "destroy", "gc");
session_start();
// proceed to use sessions normally

Save as session_user_start. php.

Now our PHP save session is complete, as long as you need to use session, include session_user_start. php. Note that this file 1 must be included in line 1 of the file, and then use it just like using session1 of the file.

The above is just a simple tutorial. In practical application, it can be encapsulated more professionally. The reference code is as follows:

SessionMysql.class.php


<?php
/**
 * SessionMysql Database storage class
 */ defined('IN_QIAN') or exit('Access Denied'); class SessionMysql {  public $lifetime = 1800; // Validity period in seconds ( s ), default 30 Minutes
 public $db;
 public $table;  /**
  * Constructor
  */
 public function __construct() {
  $this->db = Base::loadModel('SessionModel');
  $this->lifetime = Base::loadConfig('system', 'session_lifetime');
  session_set_save_handler(
   array(&$this, 'open'),  // Running session_start() Execute when
   array(&$this, 'close'),  // Upon completion of script execution Or Call session_write_close() Or session_destroy() Is executed, that is, at all session After the operation is completed, it is executed
   array(&$this, 'read'),  // Running session_start() Is executed when the session_start Will go when read Current session Data
   array(&$this, 'write'),  // This method is used at the end of the script and after using the session_write_close() Forced submission SESSION Execute when data is used
   array(&$this, 'destroy'), // Running session_destroy() Execute when
   array(&$this, 'gc')   // Execution probability is determined by session.gc_probability And session.gc_divisor The timing is determined by the value of open , read After that, session_start Will be executed one after another open , read And gc
  );
  session_start(); // This is also necessary. Open session , must be in session_set_save_handler Execute later
 }
 /**
  * session_set_save_handler open Method
  *
  * @param $savePath
  * @param $sessionName
  * @return true
  */
 public function open($savePath, $sessionName) {
  return true;
 }
 /**
  * session_set_save_handler close Method
  *
  * @return bool
  */
 public function close() {
  return $this->gc($this->lifetime);
 }
 /**
  * Read session_id
  *
  * session_set_save_handler read Method
  * @return string Read session_id
  */
 public function read($sessionId) {
  $condition = array(
   'where' => array(
    'session_id' => $sessionId
   ),
   'fields' => 'data'
  );
  $row = $this->db->fetchFirst($condition);
  return $row ? $row['data'] : '';
 }
 /**
  * Write session_id Value of
  *
  * @param $sessionId Conversation ID
  * @param $data Value
  * @return mixed query Execution results
  */
 public function write($sessionId, $data) {
  $userId = isset($_SESSION['userId']) ? $_SESSION['userId'] : 0;
  $roleId = isset($_SESSION['roleId']) ? $_SESSION['roleId'] : 0;
  $grouId = isset($_SESSION['grouId']) ? $_SESSION['grouId'] : 0;
  $m = defined('ROUTE_M') ? ROUTE_M : '';
  $c = defined('ROUTE_C') ? ROUTE_C : '';
  $a = defined('ROUTE_A') ? ROUTE_A : '';
  if (strlen($data) > 255) {
   $data = '';
  }
  $ip = get_ip();
  $sessionData = array(
   'session_id' => $sessionId,
   'user_id'  => $userId,
   'ip'   => $ip,
   'last_visit' => SYS_TIME,
   'role_id'  => $roleId,
   'group_id'  => $grouId,
   'm'    => $m,
   'c'    => $c,
   'a'    => $a,
   'data'   => $data,
  );
  return $this->db->insert($sessionData, 1, 1);
 }
 /**
  * Deletes the specified session_id
  *
  * @param string $sessionId Conversation ID
  * @return bool
  */
 public function destroy($sessionId) {
  return $this->db->delete(array('session_id' => $sessionId));
 }
 /**
  * Delete expired session
  *
  * @param $lifetime session Validity period (in seconds)
  * @return bool
 */
 public function gc($lifetime) {
  $expireTime = SYS_TIME - $lifetime;
  return $this->db->delete("`last_visit`<$expireTime");
 }
}

Somewhere in the system file, instantiate this class!


new SessionMysql();


Related articles: