How to Optimize and speed up PHP with OPCache

PHP 5.5 and 5.6 comes with OPCache. OPCache speeds up PHP execution by storing precompile bytecode of PHP in shared memory. Taking advantage of fast memory operations compared to hard disk operation, OPCache eliminates the process of having to read PHP scripts from the disk each time whenever a script must be executed.

In short, OPCache saves the time needed to serve PHP-powered websites!

How to enable OPCache?
This tutorial is written from Ubuntu 14.04 LTS standpoint – using php5-fpm, but it should also work for other Linux distro.

  1. First edit ‘/etc/php5/fpm/php.ini‘ file.
  2. Find “opcache” section in the PHP ini.
  3. Uncomment and change opcache.enable to opcache.enable=1
  4. Do the same for >opcache.memory_consumption, changed its value from 64 to 128 (or 256)
  5. Change opcache.interned_strings_buffer from 4 to 16
  6. Changed the opcache.max_accelerated_files to 8192

Activate OPCache with php5enmod command.

sudo php5enmod opcache

Save file and restart php5-fpm.

sudo service php5-fpm restart

PHP OPCache should be running on your server now. Here’s a reference of /etc/php/fpm/php.ini file in Ubuntu 14.04 LTS.

[opcache]
; Determines if Zend OPCache is enabled
opcache.enable=1

; Determines if Zend OPCache is enabled for the CLI version of PHP
opcache.enable_cli=0

; The OPcache shared memory storage size.
opcache.memory_consumption=128

; The amount of memory for interned strings in Mbytes.
opcache.interned_strings_buffer=16

; The maximum number of keys (scripts) in the OPcache hash table.
; Only numbers between 200 and 100000 are allowed.
opcache.max_accelerated_files=8192

BONUS: How to verify whether PHP OPCache is running ??
You can verify whether OPCache is running by using opcache-status by Rasmus Lerdorf. Just drop the script in one of your web directory and browse. If you’re not a Git fan, I’ve also have taken the liberty of mirroring the download: opcache-status.zip

opcache-status screenshot
opcache-status-ss