PHP and APC – Tutorial

APC is most widely known for allowing the end user to be able to track the progress of file transfers. APC, which stands for “Alternative PHP Cache” does much more than that. Complex and large scale websites can benefit from it’s ability to cache data and as well as its optimization of PHP code.

If you are looking for a tutorial on using APC for tracking file upload progress then visit my tutorial for File Upload Progress

APC does not have a large host of commands, this does not ease the complexity. We will take a look at a few simple functions and explain their use, in addition I will try to explain the practical reasons to use them. There are a few warnings to adhere to when trying utilize alternative PHP cache, these will also be discussed.

APC Functions – The Basics

In order to write to and read from the cache we will use two separate functions, the first “apc_store” will allow us to store a variable. The command “apc_fetch” will retrieve it. These functions are able to store arrays as well, however multidimensional arrays are a different story. A basic example on how to store a single variable would be as follows:

$cachevar = “This is my cached variable”;
apc_store(“test”, $cachevar); 

//To retreive our cached variable we will call it by its name “test”
var_dump(apc_fetch(“test”));

The variable above will remain in the cache until we either clear it or restart our server. We can also set a time limit on the cached variable so that it will be removed after x amount of time. This is called the “ttl”(time to live) and is used: apc_store(“test”, $cachevar, 30); .

To delete the variable stored in the cache you would simply call the apc_delete function and specify the key:

apc_delete(“test”);

As we mentioned above it is possible to store arrays, anything more than a single level deep will not work. A way to overcome this is by first serializing your data. PHP usesserialize as well as unserialize to allow a work around for arrays.

A Practical Use
Instead of using sessions or a database to collect user information you could store their data within the cache for a given time period, say 10 minutes. You could collect the users IP address or a password from the user which will allow you to set the key for your apc_store function. The user will then have x amount of time to complete registration based on the “ttl” and they can exit and return the site, even close their browser, and their registration info will still be available.

 

APC… The Need For Speed

There has been a lot of debate over APC and if installing it actually speeds up the execution of PHP. By default APC will compile and store each PHP file as it is executed for the first time. The compiled version is stored in bytecode and placed in shared memory.

To me this proves one major point, if the code is pre-compiled then there is no need to compile every time the code is hit by a user. This means more available time for the CPU to handle other tasks thus reducing server load.

APC will allow you to compile files manually which is great for larger sites running on multiple servers. Before the server is brought back online it is possible to compile everything, which will reduce the initial load. Even smaller sites can compile additions to increase performance when expanding. To compile a file we would use the command apc_compile and simply feed it a filename:

$file = “myfile.php”;
apc_compile_file($file); 

//To compile a complete directory we would use apc_compile_dir
$recursively = true;
apc_compile_dir($dir, $recursively);

A great example on recursively compiling an entire site can be found in the PHP manual for APC.

Speed
For PHP intensive sites you should notice a large decrease in execution time after installing APC. For maximum speed enabling APC under FastCGI can produce great results. There does seem to be a conflict when trying to run this on older versions of PHP. Running 5.2+ you should not run into any problems.

 

Cache Information and Commands

In order to tell what resources are available or the remaining size of your cache you will need to run a command or two. APC comes with a couple functions which allows you to extract the current state of the cache.

The first command is: apc_cache_info(), which will return cached files as well as the number of hits and misses. Below will show how to view cached files.

foreach ($cache[‘cache_list’] as $file=>$num) {
echo(“<b>File Number:</b> $file<br/>”);
foreach ($cache[‘cache_list’][$file] as $data=>$info){
echo(“<b>$data:</b> $info<br/>”);
}

//Below is an example of what the output would look like for each file:

//File Number: 1
//filename: filename
//device: 344467735
//inode: 11834
//type: file
//num_hits: 3
//mtime: 1249415260
//creation_time: 1252725219
//deletion_time: 0
//access_time: 1252725234
//ref_count: 0
//mem_size: 3877

The second command we can use is apc_sma_info() which will tell you about the shared memory allocation:

print_r(apc_sma_info());http://scriptperfect.com/2009/09/php-and-apc-tutorial/

//This will return something like the following:
Array
(
[num_seg] => 1
[seg_size] => 31457280
[avail_mem] => 31448408
[block_lists] => Array
(
[0] => Array
(
[0] => Array
(
[size] => 31448408
[offset] => 8864
)

)

)

)

 

Cleaning Up

There are several ways to clear the cache. The easiest which happens automatically is when your server is restarted. The second is using the apc_clear_cache() function. Using APC’s built in function can be very time consuming especially for large sites. Rebooting in many cases will clear the cache much faster then using this command.

Final Thoughts

While APC provides some great tools for speeding up PHP it still has some room for improvement. Using this tool will provide an increase in server performance and it’s functionality can even be implemented into the user experience. I am waiting to see what else others can do with this tools, if you find any innovative uses please leave us a comment!

Leave a comment