Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg

PHP : Function Reference : Alternative PHP Cache

Alternative PHP Cache


The Alternative PHP Cache (APC) is a free and open opcode cache for PHP. It was conceived of to provide a free, open, and robust framework for caching and optimizing PHP intermediate code.


This » PECL extension is not bundled with PHP.

Information for installing this PECL extension may be found in the manual chapter titled Installation of PECL extensions. Additional information such as new releases, downloads, source files, maintainer information, and a CHANGELOG, can be located here: »

The DLL for this PECL extension may be downloaded from either the » PHP Downloads page or from »


On Windows, APC needs a temp path to exist, and be writable by the web server. It checks TMP, TEMP, USERPROFILE environment variables in that order and finally tries the WINDOWS directory if none of those are set.


For more in-depth, highly technical implementation details, see the » developer-supplied TECHNOTES file .

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Although the default APC settings are fine for many installations, serious users should consider tuning the following parameters.

There are two main decisions you have to make. First, how much shared memory do you want to set aside for APC, and second, whether you want APC to check if a file has been modified on every request. The two ini directives involved here are apc.shm_size and apc.stat. Read the sections on these two directives carefully below.

Once you have a running server, you should copy the apc.php script that comes with the extension to somewhere in your docroot and load it up in your browser. It provides you with a detailed look at what is happening in your cache. If you have GD enabled in PHP, it will even have pretty graphs. First thing to check is of course that it is actually caching files. Assuming it is working you should then pay close attention to the Cache full count number on the left. That tells you the number of times the cache has filled up and has had to forcefully clean up any entries not accessed within the last apc.ttl seconds. You should configure your cache to minimize this number. If you are constantly filling your cache, the resulting cache churn is going to hurt performance. You should either set more memory aside for APC, or use apc.filters to cache fewer scripts.

Table 18. APC configuration options

Name Default Changeable Changelog
apc.enabled "1" PHP_INI_SYSTEM PHP_INI_SYSTEM in APC 2. PHP_INI_ALL in APC <= 3.0.12.
apc.shm_segments "1" PHP_INI_SYSTEM  
apc.shm_size "30" PHP_INI_SYSTEM  
apc.optimization "0" PHP_INI_ALL PHP_INI_SYSTEM in APC 2. Removed in APC 3.0.13.
apc.num_files_hint "1000" PHP_INI_SYSTEM  
apc.user_entries_hint "4096" PHP_INI_SYSTEM Available since APC 3.0.0.
apc.ttl "0" PHP_INI_SYSTEM Available since APC 3.0.0.
apc.user_ttl "0" PHP_INI_SYSTEM Available since APC 3.0.0.
apc.gc_ttl "3600" PHP_INI_SYSTEM  
apc.cache_by_default "1" PHP_INI_ALL PHP_INI_SYSTEM in APC <= 3.0.12. Available since APC 3.0.0.
apc.filters NULL PHP_INI_SYSTEM  
apc.mmap_file_mask NULL PHP_INI_SYSTEM  
apc.slam_defense "0" PHP_INI_SYSTEM Available since APC 3.0.0.
apc.file_update_protection "2" PHP_INI_SYSTEM Available since APC 3.0.6.
apc.enable_cli "0" PHP_INI_SYSTEM Available since APC 3.0.7.
apc.max_file_size "1M" PHP_INI_SYSTEM Available since APC 3.0.7.
apc.stat "1" PHP_INI_SYSTEM Available since APC 3.0.10.
apc.write_lock "1" PHP_INI_SYSTEM Available since APC 3.0.11.
apc.report_autofilter "0" PHP_INI_SYSTEM Available since APC 3.0.11.
apc.include_once_override "0" PHP_INI_SYSTEM Available since APC 3.0.12.
apc.rfc1867 "0" PHP_INI_SYSTEM Available since APC 3.0.13.
apc.rfc1867_prefix "upload_" PHP_INI_SYSTEM  
apc.rfc1867_freq "0" PHP_INI_SYSTEM  
apc.localcache "0" PHP_INI_SYSTEM Available since APC 3.0.14.
apc.localcache.size "512" PHP_INI_SYSTEM Available since APC 3.0.14.

For further details and definitions of the PHP_INI_* constants, see the Appendix I, php.ini directives.

Here's a short explanation of the configuration directives.

apc.enabled boolean

apc.enabled can be set to 0 to disable APC. This is primarily useful when APC is statically compiled into PHP, since there is no other way to disable it (when compiled as a DSO, the extension line in php.ini can just be commented-out).

apc.shm_segments integer

The number of shared memory segments to allocate for the compiler cache. If APC is running out of shared memory but you have already set apc.shm_size as high as your system allows, you can try raising this value.

apc.shm_size integer

The size of each shared memory segment in MB. By default, some systems (including most BSD variants) have very low limits on the size of a shared memory segment.

apc.optimization integer

The optimization level. Zero disables the optimizer, and higher values use more aggressive optimizations. Expect very modest speed improvements. This is experimental.

apc.num_files_hint integer

A "hint" about the number of distinct source files that will be included or requested on your web server. Set to zero or omit if you're not sure; this setting is mainly useful for sites that have many thousands of source files.

apc.user_entries_hint integer

Just like apc.num_files_hint, a "hint" about the number of distinct user cache variables to store. Set to zero or omit if not sure.

apc.ttl integer

The number of seconds a cache entry is allowed to idle in a slot in case this cache entry slot is needed by another entry. Leaving this at zero means that your cache could potentially fill up with stale entries while newer entries won't be cached.

apc.user_ttl integer

The number of seconds a user cache entry is allowed to idle in a slot in case this cache entry slot is needed by another entry. Leaving this at zero means that your cache could potentially fill up with stale entries while newer entries won't be cached.

apc.gc_ttl integer

The number of seconds that a cache entry may remain on the garbage-collection list. This value provides a fail-safe in the event that a server process dies while executing a cached source file; if that source file is modified, the memory allocated for the old version will not be reclaimed until this TTL reached. Set to zero to disable this feature.

apc.cache_by_default boolean

On by default, but can be set to off and used in conjunction with positive apc.filters so that files are only cached if matched by a positive filter.

apc.filters string

A comma-separated list of POSIX extended regular expressions. If any pattern matches the source filename, the file will not be cached. Note that the filename used for matching is the one passed to include/require, not the absolute path. If the first character of the expression is a + then the expression will be additive in the sense that any files matched by the expression will be cached, and if the first character is a - then anything matched will not be cached. The - case is the default, so it can be left off.

apc.mmap_file_mask string

If compiled with MMAP support by using --enable-mmap this is the mktemp-style file_mask to pass to the mmap module for determing whether your mmap'ed memory region is going to be file-backed or shared memory backed. For straight file-backed mmap, set it to something like /tmp/apc.XXXXXX (exactly 6 Xs). To use POSIX-style shm_open/mmap put a .shm somewhere in your mask. e.g. /apc.shm.XXXXXX You can also set it to /dev/zero to use your kernel's /dev/zero interface to anonymous mmap'ed memory. Leaving it undefined will force an anonymous mmap.

apc.slam_defense integer

On very busy servers whenever you start the server or modify files you can create a race of many processes all trying to cache the same file at the same time. This option sets the percentage of processes that will skip trying to cache an uncached file. Or think of it as the probability of a single process to skip caching. For example, setting apc.slam_defense to 75 would mean that there is a 75% chance that the process will not cache an uncached file. So, the higher the setting the greater the defense against cache slams. Setting this to 0 disables this feature.

Deprecated by apc.write_lock.

apc.file_update_protection integer

When you modify a file on a live web server you really should do so in an atomic manner. That is, write to a temporary file and rename (mv) the file into its permanent position when it is ready. Many text editors, cp, tar and other such programs don't do this. This means that there is a chance that a file is accessed (and cached) while it is still being written to. This apc.file_update_protection setting puts a delay on caching brand new files. The default is 2 seconds which means that if the modification timestamp (mtime) on a file shows that it is less than 2 seconds old when it is accessed, it will not be cached. The unfortunate person who accessed this half-written file will still see weirdness, but at least it won't persist. If you are certain you always atomically update your files by using something like rsync which does this correctly, you can turn this protection off by setting it to 0. If you have a system that is flooded with io causing some update procedure to take longer than 2 seconds, you may want to increase this a bit.

apc.enable_cli integer

Mostly for testing and debugging. Setting this enables APC for the CLI version of PHP. Normally you wouldn't want to create, populate and tear down the APC cache on every CLI request, but for various test scenarios it is handy to be able to enable APC for the CLI version of APC easily.

apc.max_file_size integer

Prevent files larger than this value from getting cached. Defaults to 1M.

apc.stat integer

Be careful if you change this setting. The default is for this to be On which means that APC will stat (check) the script on each request to see if it has been modified. If it has been modified it will recompile and cache the new version. If you turn this setting off, it will not check. That means that in order to have changes become active you need to restart your web server. On a production server where you rarely change the code, turning stats off can produce a significant performance boost.

For included/required files this option applies as well, but note that if you are using relative path includes (any path that doesn't start with / on Unix) APC has to check in order to uniquely identify the file. If you use absolute path includes APC can skip the stat and use that absolute path as the unique identifier for the file.

apc.write_lock boolean

On busy servers when you first start up the server, or when many files are modified, you can end up with all your processes trying to compile and cache the same files. With write_lock enabled, only one process at a time will try to compile an uncached script while the other processes will run uncached instead of sitting around waiting on a lock.

apc.report_autofilter boolean

Logs any scripts that were automatically excluded from being cached due to early/late binding issues.

apc.include_once_override boolean

Optimize include_once() and require_once() calls and avoid the expensive system calls used.

apc.rfc1867 boolean

RFC1867 File Upload Progress hook handler is only available if you compiled APC against PHP 5.2.0 or later. When enabled, any file uploads which includes a field called APC_UPLOAD_PROGRESS before the file field in an upload form will cause APC to automatically create an upload_key user cache entry where key is the value of the APC_UPLOAD_PROGRESS form entry.

Note that the file upload tracking is not threadsafe at this point, so new uploads that happen while a previous one is still going will disable the tracking for the previous.

Example 208. An apc.rfc1867 example


The above example will output something similar to:

   [total] => 1142543
   [current] => 1142543
   [rate] => 1828068.8
   [filename] => test
   [name] => file
   [temp_filename] => /tmp/php8F
   [cancel_upload] => 0
   [done] => 1

apc.rfc1867_prefix string

Key prefix to use for the user cache entry generated by rfc1867 upload progress functionality.

apc.rfc1867_name string

Specify the hidden form entry name that activates APC upload progress and specifies the user cache key suffix.

apc.rfc1867_freq string

The frequency that updates should be made to the user cache entry for upload progress. This can take the form of a percentage of the total file size or a size in bytes optionally suffixed with 'k', 'm', or 'g' for kilobytes, megabytes, or gigabytes respectively (case insensitive). A setting of 0 updates as often as possible, which may cause slower uploads.

apc.localcache boolean

This enables a lock-free local process shadow-cache which reduces lock contention when the cache is being written to.

apc.localcache.size integer

The size of the local process shadow-cache, should be set to a sufficently large value, approximately half of apc.num_files_hint.

Resource Types

This extension has no resource types defined.

Predefined Constants

This extension has no constants defined.

Table of Contents

apc_add — Cache a variable in the data store (only if it's not stored)
apc_cache_info — Retrieves cached information (and meta-data) from APC's data store
apc_clear_cache — Clears the APC cache
apc_compile_file — Stores a file in the bytecode cache, bypassing all filters.
apc_define_constants — Defines a set of constants for retrieval and mass-definition
apc_delete — Removes a stored variable from the cache
apc_fetch — Fetch a stored variable from the cache
apc_load_constants — Loads a set of constants from the cache
apc_sma_info — Retrieves APC's Shared Memory Allocation information
apc_store — Cache a variable in the data store

Code Examples / Notes » ref.apc


Keep in mind to always prefix or suffix your cache key names with something specific to your site/app/setup, to avoid the risk of your apc cache entries being overwritten/deleted/modified by someone else on the same server.
Assume we have some code like this:
apc_store('config', $cfg);
Now assume someone else on the same server is also using 'config' as the key passed to an apc_store(), apc_delete() (etc.) call in some other piece of code on the whole server.
Since you're both working on the exact same cache entry, all sorts of wierd things can happen, but the problem is not in your code at all.


It seems there are issues when using APC to cache database result sets as PDOStatements. Any attempts I have made always result in an exception being thrown with the message: 'You cannot serialize or unserialize PDOStatement instances'


In windows, if you load php_apc.dll but do not enable it, apache may crash when attempting to restart or stop.
So, if you've not enabled APC but are loading it, comment out the loading.

bjoern dot andersen

In IIS6 you can't use php_apc.dll with application pools or webgardens (Multi-Instance/Multi-Threading). Maybe this applies even to all Multithreading environments - i don't know.
When you try it, the Application pools terminate when requests run simultaneously.


If you don't want any APC info visible without logging in, insert this code at line 173 of apc.php:
echo '<div class="authneeded">You need to login to see the user values here!<br/>&nbsp;<br/>';
put_login_link("Login now!");
echo '</div>';


If you don't really need caching and plan to use it for one page only, you could try an alternative; writing a file and then flushing it back if specified time hasn't passed. I use it to read and parse third party websites, to check for new subtitles and output a RSS xml file.
if ((is_file($_SERVER['SCRIPT_FILENAME'].'.cached'))
&& (time()-filemtime($_SERVER['SCRIPT_FILENAME'].'.cached') < 3600))
// (the php script itself goes here)
echo $out;
$fp = fopen($_SERVER['SCRIPT_FILENAME'].'.cached', 'w');
fwrite($fp, $out);
Note, that this only works for pages, which are without GET or POST variables, sessions, etc. You can change the number of seconds the cache works for (3600 = an hour). Also, use "$out.=" instead of "echo" command. Just store all output to that variable (if you need to use it inside a function, use "global $out" instead).
This workaround was written in about 5 minutes and may contain bugs.


An improvement on ashus at atlas dot cz's script below would be to add around the script that generates the output:
ob_start ();
// script goes here
$out = ob_get_content();
ob_end_clean ();
That way you can continue to use echo rather than string concatenation, and it should be a little faster.

Change Language

Follow Navioo On Twitter
.NET Functions
Apache-specific Functions
Alternative PHP Cache
Advanced PHP debugger
Array Functions
Aspell functions [deprecated]
BBCode Functions
BCMath Arbitrary Precision Mathematics Functions
PHP bytecode Compiler
Bzip2 Compression Functions
Calendar Functions
CCVS API Functions [deprecated]
Class/Object Functions
Classkit Functions
ClibPDF Functions [deprecated]
COM and .Net (Windows)
Crack Functions
Character Type Functions
Cybercash Payment Functions
Credit Mutuel CyberMUT functions
Cyrus IMAP administration Functions
Date and Time Functions
DB++ Functions
Database (dbm-style) Abstraction Layer Functions
dBase Functions
DBM Functions [deprecated]
dbx Functions
Direct IO Functions
Directory Functions
DOM Functions
DOM XML Functions
enchant Functions
Error Handling and Logging Functions
Exif Functions
Expect Functions
File Alteration Monitor Functions
Forms Data Format Functions
Fileinfo Functions
filePro Functions
Filesystem Functions
Filter Functions
Firebird/InterBase Functions
Firebird/Interbase Functions (PDO_FIREBIRD)
FriBiDi Functions
FrontBase Functions
FTP Functions
Function Handling Functions
GeoIP Functions
Gettext Functions
GMP Functions
gnupg Functions
Haru PDF Functions
hash Functions
Hyperwave Functions
Hyperwave API Functions
i18n Functions
IBM Functions (PDO_IBM)
iconv Functions
ID3 Functions
IIS Administration Functions
Image Functions
Imagick Image Library
Informix Functions
Informix Functions (PDO_INFORMIX)
Ingres II Functions
IRC Gateway Functions
PHP / Java Integration
JSON Functions
LDAP Functions
libxml Functions
Lotus Notes Functions
LZF Functions
Mail Functions
Mailparse Functions
Mathematical Functions
MaxDB PHP Extension
MCAL Functions
Mcrypt Encryption Functions
MCVE (Monetra) Payment Functions
Memcache Functions
Mhash Functions
Mimetype Functions
Ming functions for Flash
Miscellaneous Functions
mnoGoSearch Functions
Microsoft SQL Server Functions
Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
Mohawk Software Session Handler Functions
mSQL Functions
Multibyte String Functions
muscat Functions
MySQL Functions
MySQL Functions (PDO_MYSQL)
MySQL Improved Extension
Ncurses Terminal Screen Control Functions
Network Functions
Newt Functions
NSAPI-specific Functions
Object Aggregation/Composition Functions
Object property and method call overloading
Oracle Functions
ODBC Functions (Unified)
ODBC and DB2 Functions (PDO_ODBC)
OpenAL Audio Bindings
OpenSSL Functions
Oracle Functions [deprecated]
Oracle Functions (PDO_OCI)
Output Control Functions
Ovrimos SQL Functions
Paradox File Access
Parsekit Functions
Process Control Functions
Regular Expression Functions (Perl-Compatible)
PDF Functions
PDO Functions
Phar archive stream and classes
PHP Options&Information
POSIX Functions
Regular Expression Functions (POSIX Extended)
PostgreSQL Functions
PostgreSQL Functions (PDO_PGSQL)
Printer Functions
Program Execution Functions
PostScript document creation
Pspell Functions
qtdom Functions
Rar Functions
GNU Readline
GNU Recode Functions
RPM Header Reading Functions
runkit Functions
SAM - Simple Asynchronous Messaging
Satellite CORBA client extension [deprecated]
SCA Functions
SDO Functions
SDO XML Data Access Service Functions
SDO Relational Data Access Service Functions
SESAM Database Functions
PostgreSQL Session Save Handler
Session Handling Functions
Shared Memory Functions
SimpleXML functions
SNMP Functions
SOAP Functions
Socket Functions
Standard PHP Library (SPL) Functions
SQLite Functions
SQLite Functions (PDO_SQLITE)
Secure Shell2 Functions
Statistics Functions
Stream Functions
String Functions
Subversion Functions
Shockwave Flash Functions
Swish Functions
Sybase Functions
TCP Wrappers Functions
Tidy Functions
Tokenizer Functions
Unicode Functions
URL Functions
Variable Handling Functions
Verisign Payflow Pro Functions
vpopmail Functions
W32api Functions
WDDX Functions
win32ps Functions
win32service Functions
xattr Functions
xdiff Functions
XML Parser Functions
XML-RPC Functions
XMLReader functions
XMLWriter Functions
XSL functions
XSLT Functions
YAZ Functions
YP/NIS Functions
Zip File Functions
Zlib Compression Functions
eXTReMe Tracker