Speed up your PHP application with Zend OpCache

The Zend OpCache provides faster PHP execution through opcode caching and optimization. It improves PHP performance by storing precompiled script bytecode in the shared memory.

PHP 5.5 comes with OpCache out of the box. I have PHP 5.4 still, but I wanted to install Zend OpCache to get some more performance out of my server.

Install

Note: Check which version is the latest here. I'm installing 7.0.2.

# Install "pecl" via php-pear
$ sudo apt-get install -y php-pear

# Install build dependencies
$ sudo apt-get install -y build-essential php5-dev

# Install Zend OpCache
$ sudo pecl install zendopcache-7.0.2

Configure

Now that it's installed, we need to set up its configuration. Ubuntu (and Debian?) has a convention to put all conf files in /etc/php5/conf.d, which are symlinked from /etc/php5/mods-available. Here's how to set that up:

First, find the location of opcache.so:

$ sudo find / -name 'opcache.so'
/usr/lib/php5/20100525/opcache.so # On my server with php 5.4

Once you have the location, you can add that to the conf file for opcache:

# Create & edit the following files:
$ sudo vim /etc/php5/mods-available/opcache.ini

# Add the following to opcache.ini
zend_extension=/usr/lib/php5/20100525/opcache.so # File path from above
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
opcache.fast_shutdown=1
opcache.enable_cli=1

In case your application (or the framework it is built on) only uses annotations at development time, you can achieve even better performance by adding opcache.save_comments=0 in your PHP configuration file as well.

Now that the INI file is created, symlink it to its proper place:

$ sudo ln -s ../mods-available/opcache.ini 20-opcache.ini

Lastly, I happen to be running php5-fpm with Nginx, so I need to restart the PHP service for the changes to take effect:

$ sudo service php5-fpm restart
# Alternatively: /etc/init.d/php5-fpm restart

If you're running PHP in Apache, just give that a restart:

$ sudo service apache2 restart
# Alternatively: /etc/init.d/apache2 restart

Confirm Installed

To confirm it's installed, run php -v, and you should get some information about Zend OpCache being installed:

$ php -v
PHP 5.4.17RC1 (cli) (built: Jun 22 2013 19:27:26) 
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologies
	with Zend OPcache v7.0.2, Copyright (c) 1999-2013, by Zend Technologies

Cleaning up

In production, you may not want the build dependencies hanging around. You can rid of the ones installed above by running:

$ sudo apt-get remove --purge build-essential php5-dev

Example Improvement!

Here's what happened here after installing Zend OpCache on the fideloper.com server:

opcache improvement on fideloper.com

Resources

  1. PHP 5.5 OpCache
  2. Article on Installation (German)
  3. Documentation