Sobes.tech
Junior

How to make sessions not stored in files?

sobes.tech AI

Answer from AI

Other storage mechanisms can be used:

  • Database. A common option, easily scalable and allows centralized session management.
  • Cache servers. For example, Redis or Memcached. Provide high-speed session data read/write.
  • Memory. For small applications or in dev environments.

To do this, configure the session.save_handler directive and, if necessary, session.save_path in php.ini or using the session_set_save_handler() function.

Example of using Redis as storage via php.ini:

session.save_handler = redis
session.save_path = "tcp://localhost:6379"

When using session_set_save_handler(), you need to implement an interface for working with the chosen storage (read, write, open, close, destroy, gc):

<?php
// Example implementation for Redis using session_set_save_handler
class RedisSessionHandler implements SessionHandlerInterface
{
    private $redis;
    private $ttl = 3600; // Session lifetime in seconds

    public function open($path, $name)
    {
        $this->redis = new Redis();
        return $this->redis->connect('localhost', 6379);
    }

    public function close()
    {
        $this->redis->close();
        return true;
    }

    public function read($id)
    {
        return $this->redis->get($id);
    }

    public function write($id, $data)
    {
        return $this->redis->setex($id, $this->ttl, $data);
    }

    public function destroy($id)
    {
        return $this->redis->del($id);
    }

    public function gc($max_lifetime)
    {
        // Redis automatically manages key expiration,
        // so this method can be empty if TTL is set in write.
        return true;
    }
}

$handler = new RedisSessionHandler();
session_set_save_handler($handler, true); // true - register handler as default
session_start();

// Continue working with the session as usual
$_SESSION['user_id'] = 123;
How to make sessions not stored in files? — PHP - sobes.tech