Web Development

Tech Tip: Optimize PHP with APC

Learn how to take advantage of the Alternative PHP Cache (APC) tool to speed up your PHP scripts.

PHP is perhaps the most popular language for Web site development among Linux developers and arguably for developers on other platforms as well. PHP is well-supported, fast, and very flexible.

However, PHP does have one drawback. Because PHP is a scripting language, it therefore compiles any given script on the fly prior to executing it. But while most modern systems can do this quickly, obtaining the most performance one can squeeze out of Web services is always a good thing.

Alternative PHP Cache (APC) is an open source caching tool available for PHP, which caches compiled scripts. So on subsequent calls, PHP only has to recompile the script if it has changed.

While this can lead to only a modest performance gain on some scripts, it can lead to a fairly significant increase on more complex scripts. Unlike some of its competitors, APC is open source and freely available. You can download the source code from the APC Web site.

A free commercial offering is also available: Zend Optimizer from Zend. (Zend is the company that wrote the engine PHP uses to compile scripts.) However, independent reports have shown that APC's gains over Zend Optimizer's can be fairly significant.

Installing APC is a snap; there's nothing to configure to make it work "out of the box." Just download the APC source code; the latest version is 2.0.4. To install APC, execute the following:

# tar xvzf APC-2.0.3.tgz
# cd APC-2.0.3
# /usr/bin/phpize
# ./configure --enable-apc
# make
# make install

If your PHP installation isn't located in /usr, you must call phpize from the bin/ directory under your installation directory. For instance, if you've installed PHP in /usr/local/php, you would execute /usr/local/php/bin/phpize.

Next, use a text editor to edit the php.ini file (usually /etc/php.ini), and add the following to the bottom:


Save the file, and restart Apache. Then, create a file called info.php somewhere in your Web tree that contains the following:

<?php phpinfo(); ?>

Open this page in your browser. You should see a section for APC in the output. You can now take advantage of APC to speed up your PHP scripts.


Editor's Picks