caching – PHP "apc_store" and "apc_fetch" are not working as expected-ThrowExceptions

Exception or error:

I was trying to use APC but it doesn’t seem to work as I expected.

file1:

$bar = 'BAR';
apc_store('foo', $bar, 3600);
var_dump(apc_fetch('foo'));           // It works here. Displays BAR

file2:

var_dump(apc_fetch('foo'));

When I execute file2 within seconds, it returns false instead of ‘BAR’ which is the data stored in the cache.

How to solve:

It works fine 🙂 – as long as you remember that every php script executed from the command line uses it’s own cache, so you won’t be able to access data saved by script1 inside script2. (you can’t access it in a later run of script1 either as it gets cleared when the script finishes)

These caches are also separate from the cache you most likely want to use, and that’s the cache of php scripts executed via your web server.

So if you have those tests above saved in your webroot so you can access for example
http://localhost/file1.php, then
http://localhost/file2.php

It’ll work as expected.

This also means that you can’t clear out the webserver’s APC cache from the command line.
The cache (user cache or opcode cache) clearing code has to be executed via your web server.
Would it be a wget from shell, or file_get_contents() from php cli – it’s up to your taste and circumstances.

Answer:

Install this ( http://svn.php.net/viewvc/pecl/apc/trunk/apc.php?view=markup ) in a protected area of the server, set it up as describe in the comments, and that should make diagnosing your APC caching issues a breeze… or atleast give you a better insight into why something isn’t working as desired.

Leave a Reply

Your email address will not be published. Required fields are marked *