futtta's blog

Frank Goossens' Twitterless twaddle

Fun with caching in PHP with APC (and others)

with 2 comments

After installing APC, I looked through the documentation on php.net and noticed 3 interesting functions with regards to session-independent data caching in PHP;

When talking about caching, apc_delete might not be that important, as apc_store allows you to set the TTL (time to live) of the variable you’re storing. If you try to retrieve a stored variable which exceeded the TTL, APC will return FALSE, which tells you to update your cache.

All this means that adding 5 minutes worth of caching to your application could be as simple as doing;

if (($stringValue=apc_fetch($stringKey)) === FALSE) {
$stringValue = yourNormalDogSlowFunctionToGetValue($stringKey);
apc_store($stringKey,$stringValue,300);
}

From a security point-of-view however (esp. on a shared environment) the APC-functions should be considered extremely dangerous. There are no mechanisms to prevent a denial of service; everyone who “does PHP” on a server can fill the APC-cache entirely. Worse yet, using apc_cache_info you can get a list of all keys which you in turn can use to retrieve all associated values, meaning data theft can be an issue as well. But if you’re on a server of your own (and if you trust all php-scripts you install on there), the APC-functions can be sheer bliss!

And off course other opcode caching components such as XCache and eAccelerator offer similar functionality (although it’s disabled by default in eAccelerator because of the security concerns).

Possibly related twitterless twaddle:

Written by frank

October 14th, 2008 at 12:20 am

Read more about: followup,lang:en,linux,Web development

Tagged with , ,

2 Responses to “Fun with caching in PHP with APC (and others)”

  1. Luc Stroobant

    14 Oct 08 at 12:22

    APC can improve performance a lot, but it used to cause segfaults under load on the servers I used it. On some sites it could run stable for days, while on others it crashed after a few minutes…
    Some people even made auto-restart scripts to detect those problems
    http://2bits.com/articles/logwatcher-restart-apache-after-a-segmentation-fault.html

    Maybe it’s fixed in newer releases, I didn’t try the most recent versions.

  2. frank

    14 Oct 08 at 12:45

    ow, segfaults … when skimming through the pecl bugtracker for APC+segfault, there’s not a lot of open bugs lingering around any more, but i’ll better keep a close eye apache for the days (weeks) to come i guess.

Leave a Reply