What Is OPcache?
OPcache is a PHP extension that caches compiled PHP bytecode in shared memory. Without OPcache, PHP must parse and compile every script on every request. With OPcache, compiled scripts are reused from memory.
Enable OPcache
OPcache is included with PHP but may need to be enabled:
# Check if enabled
php -m | grep OPcache
# If not enabled, install it
sudo apt install -y php8.2-opcacheOptimal Configuration
Edit /etc/php/8.2/fpm/conf.d/10-opcache.ini:
opcache.enable=1
opcache.enable_cli=0
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=10000
opcache.revalidate_freq=0
opcache.validate_timestamps=0
opcache.fast_shutdown=1
opcache.save_comments=1Key Settings Explained
| Setting | Production Value | Purpose |
|---|---|---|
memory_consumption | 256 MB | RAM for cached scripts |
max_accelerated_files | 10000 | Max cached scripts (round to prime) |
validate_timestamps | 0 (prod) | Don't check if files changed |
revalidate_freq | 0 | Seconds between file checks |
Important: Cache Invalidation
With validate_timestamps=0, PHP never checks if files changed. After deploying new code, you must restart PHP-FPM:
sudo systemctl reload php8.2-fpmCheck OPcache Status
Create a temporary status page:
<?php
$status = opcache_get_status();
echo "Memory used: " . round($status['memory_usage']['used_memory'] / 1048576, 2) . " MB\n";
echo "Memory free: " . round($status['memory_usage']['free_memory'] / 1048576, 2) . " MB\n";
echo "Cached scripts: " . $status['opcache_statistics']['num_cached_scripts'] . "\n";
echo "Hit rate: " . round($status['opcache_statistics']['opcache_hit_rate'], 2) . "%\n";Performance Impact
OPcache typically improves PHP performance by 2-5x for frameworks like Laravel and WordPress. It is the single most impactful PHP optimization you can make.