Ubuntu Server: How To Enable OPcache for PHP 7 on Apache Tips, Tricks and Tutorials 23 OCT 2017

PHP is what is known as an interpreted coding language, meaning that unlike compiled apps that have already been compiled down into bytecode (i.e. you have to compile your application first so that the OS can run it), PHP scripts are only compiled and interpreted by the runtime engine on script request.

So, if you have scripts that are relatively static (i.e. you aren’t changing them very often), one good way to accelerate your PHP project is to use some sort of caching system that essentially pre-compiles your scripts down to bytecode, meaning less work come request time and thus theoretically, faster code execution.

Enter opcode caching. OPcache, originally a closed source part of the Zend Server project (under the moniker of Zend Optimizer), is an open source module that stores (caches) precompiled PHP script bytecode in shared memory, thus removing the need for PHP to first load and parse scripts on each request.

Since PHP 5.5.0, the module has come bundled with PHP (though disabled by default), meaning that for all intents and purposes, OPcache is now pretty much the standard when it comes to PHP accelerating.

To set up OPcache on an Ubuntu 16.04 server running PHP 7 over Apache, you first need to enable OPcache via the standard php.ini file. To edit the file:

sudo nano /etc/php/7.0/apache2/php.ini

To enable the module once you have the php.ini file is open, find the line reading ;opcache.enable=0, uncomment it by removing the ; and then enable by changing the 0 to 1:


There are quite a few OPcache related settings that you can change while doing the setup, with the php.ini doing a good job of explaining the role of each one. The important ones to keep track of are: opcache.memory_consumption, opcache.max_accelerated_files, and opcache_revalidate_freq.

Save your changes and then enable the module via:

sudo phpenmod opcache

Finally, restart PHP:

sudo service apache2 restart

Monitoring OPCache is a whole other story (worth a google), but the easiest way just to make sure that it is in fact running is to call phpinfo() on one of your webpages. If enabled, you’ll see a bold section under the title of Zend OPcache, with the first column “Opcode Caching” listing a value of “Up and Running”.

Related Link: PHP OPcache | Wikipedia

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don’t have time for myself any more.