Caching in PHP: Redis, Memcached, and Built-in Solutions from A to Z

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

Introduction: Why Caching is the Foundation of PHP Performance

\n\n

Every PHP developer eventually faces performance issues. Slow page loading, high server memory consumption, and frequent database queries are symptoms of a lack of proper caching. In modern web development, caching is not a luxury, but a necessity. Without it, even the most optimized code will slow down under high load.

\n\n

In this article, we will cover three key approaches to caching in PHP: Redis, Memcached, and built-in solutions (APCu, OPcache, file caching). You will learn how to choose the right tool for a specific task, see working code examples, and get practical implementation recommendations.

\n\n

1. Built-in PHP Solutions: APCu, OPcache, and File Caching

\n\n

1.1. OPcache — Bytecode Caching

\n\n

OPcache is a built-in PHP mechanism that compiles and stores compiled script bytecode in memory. Instead of parsing and compiling a PHP file each time, OPcache uses the ready result. This provides a speed increase of up to 30-50% without a single line of code.

\n\n

Configuration in php.ini:

\n
opcache.enable=1\nopcache.memory_consumption=128\nopcache.interned_strings_buffer=8\nopcache.max_accelerated_files=10000\nopcache.revalidate_freq=2
\n\n

To check OPcache operation, use the function:

\n
<?php\nvar_dump(opcache_get_status());\n?>
\n\n

1.2. APCu — Data Caching in Memory

\n\n

APCu (Alternative PHP Cache) is an extension for storing arbitrary data in shared memory. It is ideal for caching the results of heavy computations, configurations, or data that rarely changes.

\n\n

Example of caching with APCu:

\n
<?php\n// Store data in cache for 3600 seconds (1 hour)\n$data = ['users' => 1500, 'status' => 'active'];\napcu_store('app_stats', $data, 3600);\n\n// Read from cache\n$cached = apcu_fetch('app_stats');\nif ($cached === false) {\n    // Data not in cache — recompute\n    $cached = computeExpensiveData();\n    apcu_store('app_stats', $cached, 3600);\n}\n?>
\n\n

1.3. File Caching — A Simple Start Without Additional Extensions

\n\n

If you cannot install Redis or Memcached, use the file system. It is slower, but works on any hosting.

\n\n
<?php\nclass FileCache {\n    private $cacheDir;\n    \n    public function __construct($dir = '/tmp/php_cache/') {\n        $this->cacheDir = $dir;\n        if (!is_dir($dir)) {\n            mkdir($dir, 0777, true);\n        }\n    }\n    \n    public function get($key, $ttl = 3600) {\n        $file = $this->cacheDir . md5($key) . '.cache';\n        if (!file_exists($file)) return null;\n        \n        if (time() - filemtime($file) > $ttl) {\n            unlink($file);\n            return null;\n        }\n        \n        return unserialize(file_get_contents($file));\n    }\n    \n    public function set($key, $data) {\n        $file = $this->cacheDir . md5($key) . '.cache';\n        file_put_contents($file, serialize($data));\n    }\n}\n\n// Usage\n$cache = new FileCache();\n$result = $cache->get('expensive_query');\nif ($result === null) {\n    $result = $db->query('SELECT ...');\n    $cache->set('expensive_query', $result);\n}\n?>
\n\n

2. Memcached — Distributed Caching for High Loads

\n\n

2.1. What is Memcached and When to Use It

\n\n

Memcached is a distributed caching system in RAM. It operates on a key-value principle and is ideal for caching SQL query results, user sessions, and HTML fragments. Key advantages:

\n
    \n
  • Ease of installation and configuration
  • \n
  • High spee

Blogs

Book Recommendations