{
  "id": "php",
  "title": "Redis session store with PHP",
  "url": "https://redis.io/docs/latest/develop/use-cases/session-store/php/",
  "summary": "Implement a Redis-backed session store in PHP with Predis",
  "tags": [
    "docs",
    "develop",
    "stack",
    "oss",
    "rs",
    "rc"
  ],
  "last_updated": "2026-04-16T13:29:55-07:00",
  "children": [],
  "page_type": "content",
  "content_hash": "910d849371f3076d8d46de5e5c25fe0c432edf33000a1e7bda417bfb22f6bac9",
  "sections": [
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "This guide shows you how to implement a Redis-backed session store in PHP with [Predis](https://redis.io/docs/latest/develop/clients/php). It includes a small local web server using PHP's built-in development server so you can see the session lifecycle end to end."
    },
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "Session storage is a common Redis use case for web applications. Instead of keeping session state in local process memory, you store it in Redis and send the browser only an opaque session ID in a cookie.\n\nThat gives you:\n\n* Shared sessions across multiple app servers\n* Automatic expiration using Redis TTLs\n* Fast reads and updates for small pieces of per-user state\n* A clean separation between browser cookies and server-side session data\n\nIn this example, each session is stored as a Redis hash with a key like `session:{session_id}`. The hash holds lightweight fields such as the username, page view count, timestamps, and the configured session TTL. The key also has an expiration so inactive sessions are removed automatically."
    },
    {
      "id": "how-it-works",
      "title": "How it works",
      "role": "content",
      "text": "The flow looks like this:\n\n1. A user submits a login form\n2. The server generates a random session ID with PHP's `random_bytes()`\n3. The server stores session data in Redis under `session:{id}`\n4. The server sends a `sid` cookie containing only the session ID\n5. Later requests read the cookie, load the hash from Redis, and refresh the TTL\n6. Logging out deletes the Redis key and clears the cookie\n\nBecause the cookie only contains an opaque identifier, the browser never receives the actual session data. That stays in Redis."
    },
    {
      "id": "the-php-session-store",
      "title": "The PHP session store",
      "role": "content",
      "text": "The `RedisSessionStore` class wraps the basic session operations\n([source](SessionStore.php)):\n\n[code example]\n\nThe methods return associative arrays and scalar values, which fits naturally with idiomatic PHP application code."
    },
    {
      "id": "data-model",
      "title": "Data model",
      "role": "content",
      "text": "Each session is stored in a Redis hash:\n\n[code example]\n\nThe implementation uses:\n\n* [`HSET`](https://redis.io/docs/latest/commands/hset) to create and update session fields\n* [`HGETALL`](https://redis.io/docs/latest/commands/hgetall) to load the session\n* [`HINCRBY`](https://redis.io/docs/latest/commands/hincrby) to update counters\n* [`EXPIRE`](https://redis.io/docs/latest/commands/expire) to implement sliding expiration\n* [`DEL`](https://redis.io/docs/latest/commands/del) to remove a session on logout\n\nThe store treats `created_at`, `last_accessed_at`, and `session_ttl` as reserved internal fields, so caller-provided session data cannot overwrite them."
    },
    {
      "id": "session-store-implementation",
      "title": "Session store implementation",
      "role": "content",
      "text": "The `createSession()` method generates a random session ID, writes the initial hash fields, and sets the TTL:\n\n[code example]\n\nWhen the application reads a session, it refreshes the configured TTL so active users stay logged in:\n\n[code example]\n\nThis is a simple and effective pattern for many apps. For more complex requirements, you might add separate metadata keys, rotate session IDs after login, or store less frequently accessed data elsewhere."
    },
    {
      "id": "prerequisites",
      "title": "Prerequisites",
      "role": "content",
      "text": "Before running the demo, make sure that:\n\n* Redis is running and accessible. By default, the demo connects to `localhost:6379`.\n* Predis is installed:\n\n[code example]\n\nIf your Redis server is running elsewhere, start the demo with the `REDIS_HOST` and `REDIS_PORT` environment variables."
    },
    {
      "id": "running-the-demo",
      "title": "Running the demo",
      "role": "content",
      "text": "A local demo server is included to show the session store in action\n([source](demo_server.php)):\n\n[code example]\n\nThe demo exposes a small interactive page where you can:\n\n* Start a session with a username\n* Choose a short TTL and watch the session expire\n* See the Redis-backed session data rendered in the browser\n* Increment a page-view counter stored in Redis\n* Change the active session TTL from the page\n* Log out and delete the session\n\nIf Redis is running somewhere else, pass the connection settings as environment variables:\n\n[code example]\n\nAfter starting the server, visit `http://localhost:8080`."
    },
    {
      "id": "cookie-handling",
      "title": "Cookie handling",
      "role": "content",
      "text": "The browser cookie should contain only the session ID:\n\n[code example]\n\nAvoid storing user profiles, roles, or other sensitive session data directly in cookies. Keep that information in Redis and let the cookie act only as a lookup token."
    },
    {
      "id": "production-usage",
      "title": "Production usage",
      "role": "content",
      "text": "This guide uses a deliberately small local demo so you can focus on the Redis session pattern. In production, you will usually want to harden the cookie, session lifecycle, and deployment details around it."
    },
    {
      "id": "secure-the-session-cookie",
      "title": "Secure the session cookie",
      "role": "content",
      "text": "Set cookie attributes that match your deployment and threat model:\n\n* Keep `HttpOnly` enabled so JavaScript cannot read the session cookie\n* Use the `Secure` attribute when serving your app over HTTPS\n* Choose an appropriate `SameSite` policy for your login flow and cross-site behavior"
    },
    {
      "id": "keep-session-data-lightweight",
      "title": "Keep session data lightweight",
      "role": "content",
      "text": "Redis-backed sessions work best when each session stores small, frequently accessed values:\n\n* Usernames, IDs, and feature flags are a good fit\n* Large profiles, document blobs, or activity feeds should usually live elsewhere\n* Consider storing only references if the session needs to point to larger data"
    },
    {
      "id": "handle-expiration-deliberately",
      "title": "Handle expiration deliberately",
      "role": "content",
      "text": "Sliding expiration is convenient, but it also defines how long a hijacked cookie remains useful. For production apps, consider:\n\n* Shorter inactivity TTLs for sensitive applications\n* Separate absolute expiration limits for long-lived sessions\n* Session ID rotation after login or privilege changes"
    },
    {
      "id": "use-a-framework-integration-where-appropriate",
      "title": "Use a framework integration where appropriate",
      "role": "content",
      "text": "This example keeps everything explicit so you can see the Redis session pattern clearly. In a real app, you will often wrap the same Redis operations behind middleware for Laravel, Symfony, Slim, or another PHP framework."
    },
    {
      "id": "next-steps",
      "title": "Next steps",
      "role": "content",
      "text": "You now have a complete Redis-backed session example in PHP using Predis. From here you can:\n\n* Adapt the store to your web framework\n* Add session ID rotation or absolute expiration\n* Store additional lightweight session metadata in the same Redis hash\n* Reuse the same Redis deployment across multiple application instances\n\nFor more Redis data modeling patterns, see:\n\n* [Session store overview](https://redis.io/docs/latest/develop/use-cases/session-store)\n* [PHP client guide](https://redis.io/docs/latest/develop/clients/php)\n* [Redis data types](https://redis.io/docs/latest/develop/data-types)"
    }
  ],
  "examples": [
    {
      "id": "the-php-session-store-ex0",
      "language": "php",
      "code": "<?php\n\nrequire __DIR__ . '/vendor/autoload.php';\nrequire __DIR__ . '/SessionStore.php';\n\nuse Predis\\Client;\n\n$redis = new Client([\n    'scheme' => 'tcp',\n    'host' => '127.0.0.1',\n    'port' => 6379,\n]);\n\n$store = new RedisSessionStore(redis: $redis, ttl: 1800);\n\n$sessionId = $store->createSession([\n    'username' => 'andrew',\n    'page_views' => '0',\n]);\n\n$session = $store->getSession($sessionId);\necho $session['username'] . PHP_EOL;\n\n$store->incrementField($sessionId, 'page_views');\n$store->deleteSession($sessionId);",
      "section_id": "the-php-session-store"
    },
    {
      "id": "data-model-ex0",
      "language": "text",
      "code": "session:abc123...\n  username = andrew\n  page_views = 3\n  session_ttl = 15\n  created_at = 2026-04-02T12:34:56+00:00\n  last_accessed_at = 2026-04-02T12:40:10+00:00",
      "section_id": "data-model"
    },
    {
      "id": "session-store-implementation-ex0",
      "language": "php",
      "code": "public function createSession(array $data = [], ?int $ttl = null): string\n{\n    $sessionId = $this->createSessionId();\n    $key = $this->sessionKey($sessionId);\n    $now = $this->timestamp();\n    $sessionTtl = $this->normalizeTtl($ttl);\n\n    $payload = [];\n    foreach ($data as $field => $value) {\n        if (!in_array($field, self::RESERVED_SESSION_FIELDS, true)) {\n            $payload[$field] = (string) $value;\n        }\n    }\n\n    $payload['created_at'] = $now;\n    $payload['last_accessed_at'] = $now;\n    $payload['session_ttl'] = (string) $sessionTtl;\n\n    $this->redis->pipeline(function ($pipe) use ($key, $payload, $sessionTtl): void {\n        $pipe->hset($key, $payload);\n        $pipe->expire($key, $sessionTtl);\n    });\n\n    return $sessionId;\n}",
      "section_id": "session-store-implementation"
    },
    {
      "id": "session-store-implementation-ex1",
      "language": "php",
      "code": "public function getSession(string $sessionId, bool $refreshTtl = true): ?array\n{\n    $key = $this->sessionKey($sessionId);\n    $session = $this->redis->hgetall($key);\n    if (!$this->isValidSession($session)) {\n        return null;\n    }\n\n    if (!$refreshTtl) {\n        return $session;\n    }\n\n    $sessionTtl = $this->normalizeTtl((int) $session['session_ttl']);\n    $result = $this->redis->pipeline(function ($pipe) use ($key, $sessionTtl): void {\n        $pipe->hset($key, 'last_accessed_at', $this->timestamp());\n        $pipe->expire($key, $sessionTtl);\n        $pipe->hgetall($key);\n    });\n\n    $refreshed = $result[2] ?? [];\n    return $this->isValidSession($refreshed) ? $refreshed : null;\n}",
      "section_id": "session-store-implementation"
    },
    {
      "id": "prerequisites-ex0",
      "language": "bash",
      "code": "composer require predis/predis",
      "section_id": "prerequisites"
    },
    {
      "id": "running-the-demo-ex0",
      "language": "bash",
      "code": "composer require predis/predis\nphp -S localhost:8080 demo_server.php",
      "section_id": "running-the-demo"
    },
    {
      "id": "running-the-demo-ex1",
      "language": "bash",
      "code": "REDIS_HOST=myhost REDIS_PORT=6380 php -S localhost:8080 demo_server.php",
      "section_id": "running-the-demo"
    },
    {
      "id": "cookie-handling-ex0",
      "language": "php",
      "code": "setcookie('sid', $sessionId, [\n    'expires' => 0,\n    'path' => '/',\n    'httponly' => true,\n    'samesite' => 'Lax',\n]);",
      "section_id": "cookie-handling"
    }
  ]
}
