Script Perfect

         Random snips of code and bugs

PHP and APC – Tutorial

Posted by Tim On September - 12 - 2009

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 uses serialize 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());

//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!

3,281 Responses to “PHP and APC – Tutorial”

  1. Chloe Bags says:

    Ok. I believe you are correct!…

  2. great post!
    It’s exactly what i’m looking for to get start!
    thank you!

  3. JULIAN says:

    depakote@400mg.now” rel=”nofollow”>.

    Buywithout prescription…

  4. Gucci Outlet says:

    Hi, in which did you get this data can you please assist this with some proof or you may well say some very good reference as I and other people will definitely enjoy. This data is really good and I will say will usually be valuable if we try it possib…

  5. Have no enough money to buy some real estate? Worry no more, just because that is achievable to take the credit loans to work out such kind of problems. Thence get a student loan to buy all you require.

  6. My Blog says:

    Great Post……

    I saw this really good post today….

  7. Initial issue , A big thanks to you to open my eyes….

  8. GABRIEL says:

    Benuryl

    Buywithout prescription…

  9. DONALD says:

    Zyrtec

    Buygeneric drugs…

  10. GLENN says:

    Zyrtec

    Buygeneric pills…

  11. DAN says:

    zovirax acyclovir

    Buydrugs without prescription…

  12. This can be definately a single in the finest blogs I have sen in ages online. Retain up the good posts….

  13. JAMIE says:

    Zyrtec

    Buygeneric drugs…

  14. Intimately, the publish is really the most effective on this precious subject. I concur together with your conclusions and will eagerly appear forward for a coming updates!…

  15. Your place is valueble for me. Thanks!…

  16. As usual this was a thoughtful write-up these days. You make me want to maintain coming back and forwarding it my followers…….

  17. Hi…

    I saw this really good post today….

  18. Intriguing post. I have been searching for some good resources for solar panels and discovered your blog. Planning to bookmark this one!…

    I REALLY liked your post and blog! It took me a minute bit to find your site…but I bookmarked it. Would you mind if I posted a link back to your post? …

  19. Direct Download Movies…

    [...]while the sites we link to below are completely unrelated to ours, we think they are worth a read, so have a look[...]…

  20. Online Movie Downloads…

    [...]the time to read or visit the content or sites we have linked to below the[...]…

  21. Download Full Movies…

    [...]below you’ll find the link to some sites that we think you should visit[...]…

  22. RANDY says:

    Vitamin B

    Buygeneric drugs…

  23. BRYAN says:

    side effect of zoloft

    Buyno prescription…

  24. MANUEL says:

    Omeprazole

    Buygeneric pills…

  25. WARREN says:

    Rogaine

    Buydrugs without prescription…

  26. State Specific Jobs…

    [...]we like to honor other sites on the web, even if they aren’t related to us, by linking to them. Below are some sites worth checking out[...]…

  27. ALFONSO says:

    Pyridium

    Buydrugs without prescription…

  28. ANDY says:

    Pulmicort

    Buywithout prescription…

  29. Bed Bugs…

    [...]while the sites we link to below are completely unrelated to ours, we think they are worth a read, so have a look[...]…

  30. Potenzmittel Kamagra…

    [...]Kamagra Oral Jelly Potenzmittel als Alternative zu Viagra kaufen[...]…

  31. Auto Approve says:

    Scrapebox List…

    [...]Scrapebox Auto Approve Blogs[...]…

  32. Steve’s Blog…

    [...]just down the page, are a number of entirely unrelated sites to ours, however, they are most definitely worth looking over[...]…

  33. Pure Opinion says:

    Affordable Web Hosting…

    [...]below you’ll find the link to some sites that we think you should visit[...]…

  34. Cieaura States It’s An Excellent Post Cool…

    Excellent story, reckoned I want to link to this dont stop……

  35. Live News…

    [...] which follow you’ll see the url by some companies folks are lead to believe you could take a trip to [...] …

  36. Booted Bantam Chicken…

    [...]Good sites worth checking out[...]…

  37. Grado Sr80i says:

    Steve’s Tech Site…

    [...]while the sites we link to underneath are completely not related to ours, we think they are worth a read through, so have a glimpse[...]…

  38. World Wide Research…

    [...] following you will find the hyperlink to somewhat of an online that any of us assume this take in [...]…

  39. Cheers…

    [...]just below, are some totally unrelated sites to ours, however, they are definitely worth checking out[...]…

  40. WARREN says:

    Risperdal

    Buydrugs without prescription…

Leave a Reply

Spam protection by WP Captcha-Free

About Me

I am an independent web developer and webmaster of many sites. The main goal of Script Perfect is to provide answers to some of the hard to find questions when it comes to website design and coding.

Twitter