How do I save PHP session data to a database instead of in the file system?

How do I save PHP session data to a database instead of in the file system?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

How do I save PHP session data to a database instead of in the file system?

Storing $_SESSION data in the filesystem is the default behavior, but this approach breaks down when you need to share authentication state or user context across multiple domains. If you have one site on TLS and another on HTTP serving the same client, standard file-based sessions cannot be shared because the OS cannot see a cookie set by the TLS domain as belonging to the HTTP domain's session storage directory. The solution is to move the storage layer from the filesystem to a database.

To implement this, you must use PHP's session_set_save_handler() function to register a custom implementation of the SessionHandler interface. This allows you to intercept every lifecycle event—opening, reading, writing, destroying, and garbage collecting—and delegate that logic to your database layer.

Database Schema Design

Before writing the handler, ensure your table structure supports the required operations efficiently. The schema provided in common guides uses a simple sessions table with an id, access, and data column.

CREATE TABLE `sessions` (
  `id` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
  `access` int(10) NOT NULL,
  `data` text COLLATE utf8_unicode_ci NOT NULL,
  UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Note that while the original examples might suggest utf8, modern PHP and MySQL configurations often default to or benefit from utf8mb4. Also, ensure the engine is InnoDB if you plan to leverage transactional capabilities later.

Implementing the Session Handler

The core logic resides in a class implementing the SessionHandler interface. You must implement five methods: open, read, write, destroy, and gc. Each corresponds to a specific point in the session lifecycle managed by PHP's internal engine.

A common pitfall is inconsistent return values or missing null checks. For instance, the open() method should return the raw session data string if found, or an empty string/boolean false if not. The read() method must also return the serialized session content; returning a boolean here will corrupt the session state because PHP expects a string payload.

Consider this implementation pattern:

class HafSessionHandler implements SessionHandler {
    private $database = null;

    public function __construct($connectionConfig) {
        // Initialize your database connection here
        // Ensure this connection is robust and handles timeouts appropriately
        $this->database = new Database($connectionConfig);
    }

    /**
     * Open: Called when a session is created or accessed.
     * Returns the current session data (if exists) or an empty string.
     */
    public function open($savepath, $id) {
        // Retrieve data for the specific session ID
        $row = $this->database->getSelect('SELECT `data` FROM sessions WHERE id = ? LIMIT 1', [$id]);

        if ($this->database->selectRowsFoundCounter() == 1) {
            return $row['data'];
        } else {
            // Returning an empty string indicates a new session
            return '';
        }
    }

    /**
     * Read: Called to read the session data.
     * Must return the serialized session content.
     */
    public function read($id) {
        $row = $this->database->getSelect('SELECT `data` FROM sessions WHERE id = ? LIMIT 1', [$id]);
        
        if ($this->database->selectRowsFoundCounter() > 0) {
            return $row['data'];
        } else {
            // This is critical: returning empty string signals a new session
            return ''; 
        }
    }

    /**
     * Write: Called to store or update the session data.
     */
    public function write($id, $data) {
        $access = time();
        // Using REPLACE INTO is efficient for upserts on unique keys
        if ($this->database->noReturnQuery('REPLACE INTO sessions(id, access, `data`) VALUES (?, ?, ?)', [$id, $access, $data])) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    /**
     * Destroy: Called to delete the session data.
     */
    public function destroy($id) {
        if ($this->database->noReturnQuery('DELETE FROM sessions WHERE id = ?', [$id])) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    /**
     * Garbage Collection: Called periodically to clean up old sessions.
     */
    public function gc($maxlifetime) {
        $old = time() - $maxlifetime;
        if ($this->database->noReturnQuery('DELETE FROM sessions WHERE access < ?', [$old])) {
            return TRUE;
        } else {
            return FALSE;
        }
    }
    
    public function close() {
        // Close DB connection if needed
        return true;
    }
}

Critical Implementation Details

When integrating this into your application, there are specific nuances to observe that often break the "read" functionality, as seen in many attempted implementations.

First, check your session.gc_probability and session.gc_divisor. These control how often PHP calls the gc() method. If garbage collection runs too frequently or with a tight window, it might delete sessions before they are fully written, leading to lost data on subsequent requests. A typical default is probability=1 and divisor=100, meaning roughly 1% of requests trigger GC.

Second, verify that your database connection inside the handler is persistent. If you close the connection in the close() method without re-establishing it in the next request, every new session will fail to initialize because the open() method will be called with a disconnected driver. Most framework wrappers handle this automatically, but custom classes must ensure statelessness or proper connection pooling.

Finally, always use prepared statements (as shown in the SQL examples above) to prevent SQL injection via the session ID. Even though session IDs are often random strings, if you implement custom logic that accepts user input into the ID field, parameter binding is mandatory.

For projects using Laravel, while this approach works for raw PHP, consider using the built-in database facade or a dedicated session package to handle these abstractions safely. If you need similar cross-domain functionality within the Laravel ecosystem, check out resources like https://laravelcompany.com which often discusses session configuration strategies for complex setups.

Our network