Caching in PHP: Redis, Memcached, and Built-in Solutions

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Caching in PHP: Redis, Memcached, and Built-in Solutions



Caching is one of the key tools for improving the performance of web applications. In PHP, developers have access to several approaches: from simple file caching to powerful in-memory systems such as Redis and Memcached. In this article, we will thoroughly examine each option, provide code examples, and help you choose the optimal solution for your project.



Why is caching needed?

Without caching, each request to a website can lead to repeated computations, database queries, or external API calls. A cache allows you to save the result of an expensive operation and serve it from fast storage. Main use cases:

  • Saving SQL query results (especially aggregations and JOINs).
  • Caching HTML fragments (e.g., menus, sidebars).
  • Storing user sessions.
  • Caching external API responses.


1. Redis — The King of In-Memory Caching

Redis is a high-performance in-memory data store that supports data structures: strings, lists, hashes, sets. For PHP, there are several clients, the most popular being predis/predis (pure PHP) and phpredis (C extension).



Installation

composer require predis/predis


Example: Caching a database query result

<?phprequire 'vendor/autoload.php';

use Predis\\Client;

$redis = new Client([ 'scheme' => 'tcp', 'host' => '127.0.0.1', 'port' => 6379,]);

function getUsersFromDb() { // Simulating a long query sleep(2); return ['user1', 'user2', 'user3'];}

$cacheKey = 'users:all';$cached = $redis->get($cacheKey);

if ($cached) { $users = json_decode($cached, true); echo "From cache: ";} else { $users = getUsersFromDb(); $redis->setex($cacheKey, 3600, json_encode($users)); // TTL 1 hour echo "From database: ";}

print_r($users);


Key Redis features:

  • setex() — setting a key with a time-to-live (TTL).
  • expire() — setting TTL for an existing key.
  • del() — deleting a key.
  • incr() — atomic increment (counters).


2. Memcached — Simplicity and Speed

Memcached is another popular in-memory system, but unlike Redis, it only supports string values and has no built-in data structures. However, for simple caching, it works faster due to its minimalism.



Installing the extension

sudo apt install php-memcached# or via pecl:pecl install memcached


Example: Caching an HTML fragment

<?php$memcached = new Memcached();$memcached->addServer('127.0.0.1', 11211);

function renderMenu() { // Expensive menu generation return '<nav><ul><li>Home</li></ul></nav>';}

$menuHtml = $memcached->get('menu:main');if ($menuHtml === false) { $menuHtml = renderMenu(); $memcached->set('menu:main', $menuHtml, 600); // TTL 10 minutes}

echo $menuHtml;


Important: Memcached does not support TTL in seconds by default — the time is specified in seconds (integer). If you pass 0, the cache will be stored indefinitely.



3. APCu — Built-in Caching in PHP

APCu (Alternative PHP Cache) is an extension for caching data in the shared memory of a single server. It is ideal for single-page applications and small projects.



Installation

sudo apt install php-apcu


Example: Caching configuration

<?php$configKey = 'app:config';

if

Recommendations