Introduction

OPcache stores precompiled bytecode in memory, eliminating the need to parse PHP files on every request.

Key Concepts

  • OPcache: Stores precompiled PHP bytecode in shared memory, eliminating parsing and compilation on each request.
  • opcache.validate_timestamps: When set to 0, OPcache never checks if source files changed — maximum performance but requires restart on deploy.
  • opcache.memory_consumption: The shared memory size for cached bytecodes (default 128MB, increase for large applications).
  • opcache_reset(): Function to clear all cached bytecode, typically called during deployment.

Real World Context

OPcache is the single biggest performance improvement for any PHP application — enabling it can reduce response times by 50-70% with zero code changes. Every production PHP server should have OPcache enabled and properly configured. Without it, PHP parses and compiles every .php file on every request.

Deep Dive

Intro

OPcache stores precompiled bytecode in memory, eliminating the need to parse PHP files on every request.

How opcache works

Without OPcache:
[Request] → [Read File] → [Parse] → [Compile] → [Execute]
                                     ↑
                              (Every request)

With OPcache:
[Request] → [Read from Cache] → [Execute]
                   ↑
            (Compiled once)

Enable opcache

ini
; php.ini
zend_extension=opcache
opcache.enable=1
opcache.enable_cli=0  ; Enable for CLI scripts if needed

Production configuration

ini
; Memory allocation
opcache.memory_consumption=256      ; MB of memory for cached scripts
opcache.interned_strings_buffer=32  ; MB for interned strings
opcache.max_accelerated_files=20000 ; Max files to cache

; Performance settings
opcache.validate_timestamps=0       ; Don't check file changes (production!)
opcache.revalidate_freq=0           ; Ignored when validate_timestamps=0

; Optimization
opcache.optimization_level=0x7FFFFFFF  ; All optimizations
opcache.save_comments=0                 ; Remove comments (if not using reflection)
opcache.enable_file_override=1          ; Faster file operations

; Security
opcache.restrict_api=''             ; Restrict API to specific paths

Development configuration

ini
; Check file changes for immediate updates
opcache.validate_timestamps=1
opcache.revalidate_freq=2  ; Check every 2 seconds

Preloading (php 7.4+)

php
<?php
// preload.php
$files = [
    __DIR__ . '/vendor/autoload.php',
    __DIR__ . '/src/Entity/User.php',
    __DIR__ . '/src/Entity/Order.php',
    // Add frequently used classes
];

foreach ($files as $file) {
    opcache_compile_file($file);
}
ini
; php.ini
opcache.preload=/var/www/app/preload.php
opcache.preload_user=www-data

Monitoring opcache

php
<?php
function opcacheStats(): array
{
    if (!function_exists('opcache_get_status')) {
        return ['error' => 'OPcache not available'];
    }
    
    $status = opcache_get_status();
    
    return [
        'enabled' => $status['opcache_enabled'],
        'memory_used_mb' => $status['memory_usage']['used_memory'] / 1024 / 1024,
        'memory_free_mb' => $status['memory_usage']['free_memory'] / 1024 / 1024,
        'hit_rate' => $status['opcache_statistics']['opcache_hit_rate'],
        'scripts_cached' => $status['opcache_statistics']['num_cached_scripts'],
        'restarts' => $status['opcache_statistics']['oom_restarts'],
    ];
}

Clearing opcache

php
<?php
// Clear all cache
opcache_reset();

// Clear specific file
opcache_invalidate('/path/to/file.php', true);

// Deployment script
if (opcache_get_status()) {
    opcache_reset();
    echo "OPcache cleared\n";
}

Common Pitfalls

  1. Leaving validate_timestamps=1 in production — Checking file modification times on every request adds unnecessary stat() calls. Set to 0 and clear the cache on deploy.
  2. Insufficient memory allocation — If the cache fills up, OPcache starts evicting entries, causing recompilation. Monitor with opcache_get_status() and increase memory_consumption if needed.

Best Practices

  1. Set validate_timestamps=0 in production — Disable filesystem checks and use opcache_reset() in your deployment script to reload code.
  2. Monitor cache hit rates — Use opcache_get_status() to track cache hits, misses, and memory usage. Hit rate should be >99%.

Summary

  • OPcache stores compiled bytecode in shared memory, eliminating per-request parsing overhead.
  • Set validate_timestamps=0 in production for maximum performance.
  • Monitor cache hit rates and memory usage to ensure optimal configuration.
✓ Completed