How does php store session in a database?

SessionHandler.php the contents of the file are as follows

<?php
namespace Dry\Base;

class SessionHandler{

    private $pdo = null;

    private $lifeTime = 1440;

    public function __construct($pdo)
    {
        $this->pdo = $pdo;
        $this->lifeTime = get_cfg_var("session.gc_maxlifetime");
        session_set_save_handler(
            array($this, "open"),
            array($this, "close"),
            array($this, "read"),
            array($this, "write"),
            array($this, "destroy"),
            array($this, "gc")
        );
        register_shutdown_function("session_write_close");
    }

    public function open($save_path, $session_name)
    {
        return true;
    }

    public function close()
    {
        return true;
    }

    public function read($session_id)
    {
        $time = date("Y-m-d H:i:s");
        $sql = "select session_data from session_handler where session_id="{$session_id}" and session_expires>"{$time}" limit 1";
        $sm = $this->pdo->prepare($sql);
        $sm->execute();
        if($sm->rowCount()){
            $result = $sm->fetch();
            return $result["session_data"];
        }
        else{
            return "";
        }
    }

    public function write($session_id, $session_data)
    {
        $time = date("Y-m-d H:i:s", time()+$this->lifeTime);
        $sql = "select count(1) as total from session_handler where session_id="{$session_id}" limit 1";
        $sm = $this->pdo->prepare($sql);
        $sm->execute();
        if($sm->fetchColumn()){
            $sql="update session_handler set session_data="{$session_data}",session_expires="{$time}" where session_id="{$session_id}"";
        }
        else{
            $sql="insert into session_handler(session_id,session_data,session_expires) values("{$session_id}","{$session_data}","{$time}")";
        }
        $sm = $this->pdo->prepare($sql);
        $sm->execute();
        return true;
    }

    public function destroy($session_id)
    {
        $sql = "delete from session_handler where session_id="{$session_id}"";
        $sm = $this->pdo->prepare($sql);
        $sm->execute();
        return true;
    }

    public function gc($maxlifetime)
    {
        $time = date("Y-m-d H:i:s", time()-$maxlifetime);
        $sql = "delete from session_handler where session_expires<"{$time}"";
        $sm = $this->pdo->prepare($sql);
        $sm->execute();
        return true;
    }

}
?>

test.php the contents of the file are as follows

<?php
require_once("SessionHandler.php");

use Dry\Base\SessionHandler;

$pdo = new PDO("mysql:host=192.168.1.20;dbname=test;port=3306", "root", "1234", array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_PERSISTENT => false,
    PDO::MYSQL_ATTR_INIT_COMMAND => "set names utf8",
    PDO::ATTR_ORACLE_NULLS => PDO::NULL_TO_STRING,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
));

new SessionHandler($pdo);
session_start();

$_SESSION["name"] = "test";
echo $_SESSION["name"];
?>

session_handler the structure of the table is as follows

CREATE TABLE `session_handler` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `session_id` varchar(64) NOT NULL,
  `session_data` mediumtext,
  `session_expires` datetime NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `session_id` (`session_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
Mar.04,2021

first talk about business rationality:
session will expire after a certain period of time, and then be regenerated. This kind of data does not have much persistence significance. It is recommended to use cache. For example, redis,memcached, cache invalidation is set according to session_expires . This storage scheme is more in line with the usage scenario of session.

Let's talk about performance:
kv db: redis and memcached based on memory storage must be better than mysql (mysql in read and write performance, which is more suitable for relational, transactional business scenarios)

conclusion: it should be considered from the perspective of business reasonableness, and mysql

is not recommended.

it is not recommended to store in the database. If the site visits a lot, the database will be frequently written and read, thus affecting the performance of the database. It is generally better to use redis memcache to save. And it is also convenient to maintain the expiration time. Just set the key expiration time.


look at the concurrency of your website. Small websites don't matter. If you have a little amount, it is recommended that you still use nosql.


it's stupid to save session in a database, but if you really want to do so, you can refer to this article.
http://www.codeblogbt.com/arc.


redis these cache applications are fine. Read efficiently and expire automatically

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e880b5-46c88.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e880b5-46c88.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?