PHP: APC Configuration and Usage Tips and Tricks

This PHP APC guide is divided on four different section:
1. PHP APC Configuration
2. Enable PHP APC Statistics
3. Howto Use PHP APC User Cache
4. PHP APC Performance Testing

3. Howto Use PHP APC User Cache Examples

3.1 PHP APC User Cache Example with Numeric Values

Here is an example howto use apc_add, apc_cas, apc_fetch, apc_dec and apc_inc:

<?php
    // Add num variable to data store
    apc_add('num', 1);
 
    // Print initial value
    echo "Initial value: ", apc_fetch('num'), "<br />";
 
    // Update old value with a new value
    apc_cas('num', 1, 10);
 
    // Print just updated value
    echo "Updated value: ", apc_fetch('num'), "<br />";
 
    // Decrease a stored number
    echo "Decrease 1: ", apc_dec('num'), "<br />";
    echo "Decrease 3: ", apc_dec('num', 3), "<br />";
 
    // Increase a stored number
    echo "Increase 2: ", apc_inc('num', 2), "<br />";
    echo "Increase 1: ", apc_inc('num'), "<br />";
?>

Output:

Initial value: 1
Updated value: 10
Decrease 1: 9
Decrease 3: 6
Increase 2: 8
Increase 1: 9

3.2 PHP APC User Cache Example with String

This example shows howto use apc_fetch, apc_exists, apc_store, apc_clear_cache:

<?php
    // Check if str found from cache
    if (apc_exists('str')) {
        // Print str from cache
        echo "str from cache: ", apc_fetch('str'), "<br />";
        // Clear cache
        apc_clear_cache('user');
        // Try to fetch str again
        echo "str from cache, after user cache is cleared: ", "<br />";
        var_dump(apc_fetch('str'));
    }
    else {
        // Save str to cache and set ttl 120 seconds
        echo 'str not found from cache...saving', "<br />";
        $str = "This is just test";
        apc_store('str', $str, 120);
    }
?>

First run output:

str not found from cache...saving

Second run output:

str from cache: This is just test

3.3 PHP APC User Cache Example with Array

<?php
    // Check if arr found from cache
    if ($arr = apc_fetch('arr')) {
        echo "arr from cache: ", "<br />";
        print_r($arr);
    }
    else {
        echo 'arr not found from cache...saving', "<br />";
        $arr = array('Test 1', 'Test 2', 'Test 3');
        apc_add('arr', $arr, 120);
    }
?>

First run output:

arr not found from cache...saving

Second run output:

arr from cache:
Array ( [0] => Test 1 [1] => Test 2 [2] => Test 3 )

3.3 PHP APC User Cache Example with Object

<?php
    // Simple Person class
    class Person {
        private $name;
        private $age;
 
        public function setName($name) {
            $this->name = $name;
        }
 
        public function setAge($age) {
            $this->age = $age;
        }
 
        public function getName() {
            return $this->name;
        }
 
        public function getAge() {
            return $this->age;
        }
    }
 
    // Check if Person object found from cache
    if ($obj = apc_fetch('person')) {
        echo "Person data from cache: ", "<br />";
        echo "Name: ", $obj->getName(), "<br />";
        echo "Age: ", $obj->getAge(), "<br />";
    }
    else {
        echo 'Person data not found from cache...saving', "<br />";
        $obj = new Person;
        $obj->setName('Test Person');
        $obj->setAge(35);
        apc_add('person', $obj, 3600);
    }
?>

First run output:

Person data not found from cache...saving

Second run output:

Person data from cache: 
Name: Test Person
Age: 35

This PHP APC guide is divided on four different section:
1. PHP APC Configuration
2. Enable PHP APC Statistics
3. Howto Use PHP APC User Cache
4. PHP APC Performance Testing

Pages: 1 2 3 4

Follow If Not True Then False Updates!

Pages: 1 2 3 4

32 Comments

  1. The best thing with learning PHP programming is having a lot of people who are always willing to share their knowledge. One of the best tips on APC configuration is this one that you have made.

  2. I disagree with this:
    “Normally it’s wise cache only “small” files and this value is good to set example to default 1 Mb.”
    Why did you say that? Caching large files is also good because you are avoiding parsing these files.
    Anyway thanks for the tips :)

    • Hi Luis,

      Some cases it might be good increase apc.max_file_size value. But…

      Let’s think very normal example, VPS servers (512Mb, 1Gb, 2Gb) where you have to limit amount of APC memory (e.g. 32Mb, 64Mb 128Mb, 256Mb), and you have hundreds of files, a lot of small files (less than 1Mb) and a few large files (like 25Mb).

      Okay, you cache all files ignoring the size (set very high apc.max_file_size value), then the cache will reach maximum capacity almost constantly and it clean forcefully any entries that haven’t been accessed in the last apc.ttl seconds. This is situation where you use APC, but finally your scripts are loading much slower than without any cache, because you end up the situation where load files from disk, add files to cache and delete files from cache. Which is much heavier than just load files from disk.

      The optimal situation is a situation where your cache is almost fully used, but newer reach maximum capacity (Cache full count number is always zero) and almost all incoming requests are hits (not misses).

      But, if you have enough memory to get all your files cached, then it’s okay to set very high apc.max_file_size and cache everything. :)

  3. I installed APC on a Debian server using apt-get.

    I can’t find the apc.php file in the location you mentioned where else is this file located ?

    • Hi A.Jesin,

      On Debian check /usr/share/doc/php-apc/ path or try following (as root):

      updatedb
       
      locate apc.php
  4. Hello JR,

    I tried everything and still I couldn’t find apc.php. I even tried

    find / -name apc.php

    So finally I downloaded the APC archive from PECL’s website and used the apc.php from it.

    I have uploaded a copy of it to my blog at http://jesin.tk/apc-php-download/ for people who have installed it from the repository.

    • Hi again A.Jesin,

      Strange that Debian doesn’t include apc.php at all, but nice to hear that you got it working and even write helpful post to other Debian users who can’t get apc.php file from Debian’s on pakcages. Thanks!

      • It’s in /etc/php5/conf.d/20-apc.ini

        • Thanks Henrik!

  5. Hi. I am coming from windows and am on fedora 18. What do I use for domain-name here? domainname command states there is no domain name set. i.e. none

    • Hi Chandan Pednekar,

      Do you mean APC statistics url?

  6. Just came across your useful article while trying to resolve an APC problem.

    It seems a little odd and I’m wondering if you or anybody here has come across this. I’ve got APC Opcode cache installed fine on a VPS and I can check its working with apc.php. However if I use a local php.ini file for a vhost APC stops running altogether no matter the contents of the php.ini file (even if blank).

    Any idea what would be causing this and how to resolve it ?

    • Hi Nic,

      Based on this information, my guess is that you are not enabled php apc at all when you are using local php.ini. What if you check your phpinfo is APC module loaded at all, when you use local php.ini? Or what if you use your global php.ini as your local config, is it working then?

      So I guess that you are missing following, when you use your local php.ini:

      extension=apc.so
      • Yes JR, as I’m running a VPS I have a core php.ini and a php.ini for each vhost and I’d assumed that the contents (of a local php.ini) would just override individual parts of the core php.ini. Turns out that the existence of a local php.ini overrides all server php.ini settings and I needed to reinclude the apc module. Thanks for taking the time to answer this and everybody elses questions.

        • Hi Nic,

          Create a phpinfo() file in your document root and have a look at it.

          The first section of the file will give you information on the location of the php.ini file that is being used.

          Take a look at the sections “Loaded Configuration File” and “Scan this dir for additional .ini files”

        • You are welcome! :) Yes, it’s true that local php.ini overrides all server php.ini settings. So do you get it fully working as you wished?

          • Yes, I just pulled over the core ini and modified specific settings and all is well :-)

            • Excellent! :)

  7. Hi,

    Thanks for the tutorial, apc installed without any trouble.

    But 2 issues –

    1. Upon visiting apc stats, only one file has been cached which is apc.php itself, total free memory 30m and ignore rest of the php files. Any reason?

    2. Couldn’t find apc.ini, tried many times to locate but no such php5 or php.d directory under /etc/

    I’m running CentOS 6

    Thanks

    • Hi Harry,

      First run (as root):

      updatedb

      Could you then post output of following commands:

      locate apc
       
      php -i |grep apc
       
      rpm -qa \*apc\*
       
      uname -a
      • Many thanks for quick response: Following are the results:

        1. locate apc

        /etc/selinux/targeted/modules/active/modules/apcupsd.pp
        /home/cpeasyapache/src/libxml2-2.9.0/doc/tutorial/apc.html
        /home/cpeasyapache/src/php-5.3.26/scripts/apache/apconf-conv.sh
        /home/kashmird/public_html/administrator/components/com_mobilejoomla/cachestorage/apc.php
        /home/kashmird/public_html/libraries/joomla/cache/storage/apc.php
        /home/kashmird/public_html/libraries/joomla/session/storage/apc.php
        /opt/xml2/share/doc/libxml2-2.9.0/html/tutorial/apc.html
        /usr/local/cpanel/base/3rdparty/phpMyAdmin/libraries/import/upload/apc.php
        /usr/local/cpanel/base/horde/lib/Horde/Cache/apc.php
        /usr/local/cpanel/whostmgr/docroot/templates/dbmapcopyaccount.tmpl
        /usr/local/include/php/ext/apc
        /usr/local/include/php/ext/apc/apc_serializer.h
        /usr/local/lib/php/apc.php
        /usr/local/lib/php/.registry/.channel.pecl.php.net/apc.reg
        /usr/local/lib/php/extensions/no-debug-non-zts-20090626/apc.so
        /usr/local/lib/php/tests/APC/tests/apc53_001.phpt
        /usr/local/lib/php/tests/APC/tests/apc53_002.phpt
        /usr/local/lib/php/tests/APC/tests/apc53_003.phpt
        /usr/local/lib/php/tests/APC/tests/apc53_004.phpt
        /usr/local/lib/php/tests/APC/tests/apc53_005.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_001.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_002.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_003.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_004.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_005.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_006.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_007.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_008.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_009.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_010.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_011.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_012.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_013.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_014.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_015.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_016.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_017.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_018.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_019.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_020.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_021.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_bug62699.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_bug62699_2.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_error_010.phpt
        /usr/local/lib/php/tests/APC/tests/apc54_error_010_2.phpt
        /usr/local/lib/php/tests/APC/tests/apc_001.phpt
        /usr/local/lib/php/tests/APC/tests/apc_002.phpt
        /usr/local/lib/php/tests/APC/tests/apc_003.phpt
        /usr/local/lib/php/tests/APC/tests/apc_003b.phpt
        /usr/local/lib/php/tests/APC/tests/apc_004.phpt
        /usr/local/lib/php/tests/APC/tests/apc_005.phpt
        /usr/local/lib/php/tests/APC/tests/apc_006.phpt
        /usr/local/lib/php/tests/APC/tests/apc_007.phpt
        /usr/local/lib/php/tests/APC/tests/apc_008.phpt
        /usr/local/lib/php/tests/APC/tests/apc_009.phpt
        /usr/local/lib/php/tests/APC/tests/apc_010.phpt
        /usr/local/lib/php/tests/APC/tests/apc_bin_001.phpt
        /usr/local/lib/php/tests/APC/tests/apc_bin_002-1.inc
        /usr/local/lib/php/tests/APC/tests/apc_bin_002-2.inc
        /usr/local/lib/php/tests/APC/tests/apc_bin_002.phpt
        /usr/share/doc/libxml2-devel-2.7.6/tutorial/apc.html
        /usr/share/man/man2/swapcontext.2.gz
        /usr/share/man/man3/swapcontext.3.gz
        /usr/share/man/man3p/swapcontext.3p.gz
        /usr/share/man/man8/apcupsd_selinux.8.gz
        /usr/share/man/man8/httpd_apcupsd_cgi_script_selinux.8.gz
        /usr/share/selinux/devel/include/services/apcupsd.if
        /usr/share/selinux/targeted/apcupsd.pp.bz2
        /usr/share/vim/vim72/syntax/ldapconf.vim

        2. php -i |grep apc

        apc
        apc.cache_by_default => On => On
        apc.canonicalize => On => On
        apc.coredump_unmap => Off => Off
        apc.enable_cli => Off => Off
        apc.enabled => On => On
        apc.file_md5 => Off => Off
        apc.file_update_protection => 2 => 2
        apc.filters => no value => no value
        apc.gc_ttl => 3600 => 3600
        apc.include_once_override => Off => Off
        apc.lazy_classes => Off => Off
        apc.lazy_functions => Off => Off
        apc.max_file_size => 1M => 1M
        apc.mmap_file_mask => no value => no value
        apc.num_files_hint => 1000 => 1000
        apc.preload_path => no value => no value
        apc.report_autofilter => Off => Off
        apc.rfc1867 => Off => Off
        apc.rfc1867_freq => 0 => 0
        apc.rfc1867_name => APC_UPLOAD_PROGRESS => APC_UPLOAD_PROGRESS
        apc.rfc1867_prefix => upload_ => upload_
        apc.rfc1867_ttl => 3600 => 3600
        apc.serializer => default => default
        apc.shm_segments => 1 => 1
        apc.shm_size => 32M => 32M
        apc.slam_defense => On => On
        apc.stat => On => On
        apc.stat_ctime => Off => Off
        apc.ttl => 0 => 0
        apc.use_request_time => On => On
        apc.user_entries_hint => 4096 => 4096
        apc.user_ttl => 0 => 0
        apc.write_lock => On => On

        3. rpm -qa \*apc\* —– nothing appeared / no result

        4. uname -a

        Linux kd.teckbucket.co.uk 2.6.32-358.11.1.el6.x86_64 #1 SMP Wed Jun 12 03:34:52 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

        Thanks
        Harry

        • Thanks for this info, how and where is your php installed?

          You could create apc.ini or alternatively add your configuration to php.ini. Your php apc module is currently enabled with default config.

          • Thanks for the response.

            PHP was pre-installed on the server. I guess it’s under /usr/local/lib/php (not sure, but seems to be).

            Yes, php apc module is enabled, ain’t suppose to cache php files even with default config ?

            Can I create apc.ini at the same location as php.in ? if not where should I create and how do I relate it to php.ini.

            • Create a phpinfo file in your document root and access it via web browser.
              Search for the option which says “Scan this dir for additional .ini files” this contains a directory location inside which config files of various PHP modules exist.

              • No ini files.

                Scan this dir for additional .ini files – (none)

                Additional .ini files parsed – (none)

    • Hi Harry,

      I’m using apc on Debian and the apc.ini file is named as 20-apc.ini which is located inside /etc/php5/conf.d/20-apc.ini so try using find /etc -name *apc.ini to locate the file.

      • Hi Jesin,

        Thanks for the response.

        1. I did checked many times under /etc/. Unfortunately, no such directory php or php5 found.

        2. Tried – find /etc -name *apc.ini

        – no result appeared

        Thanks
        Harry

  8. Thanks for the great tutorial.. I have installed successfully in my server :)

  9. Dear A.Jesin ,
    use SSH find command is too usefu1
    for example :
    find -name / apc.php

    900d 1u(k

  10. Hey JR please guide on Centos.

    Here is My Centos Config of APCU.ini


    ; Enable APCu extension module
    extension = apcu.so

    ; This can be set to 0 to disable APCu
    apc.enabled=1

    ; Setting this enables APCu for the CLI version of PHP
    ; (Mostly for testing and debugging).
    ;apc.enable_cli=0

    ; Sets the path to text files containing caches to load from disk upon
    ; initialization of APCu. preload_path should be a directory where each
    ; file follows $key.data where $key should be used as the entry name
    ; and the contents of the file contains serialized data to use as the value
    ; of the entry.
    ;apc.preload_path=

    ; The size of each shared memory segment, with M/G suffixe
    ;apc.shm_size=32M

    ; 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.
    ;apc.ttl=0

    ; The number of seconds that a cache entry may remain on the
    ; garbage-collection list.
    ;apc.gc_ttl=3600

    ; If you begin to get low on resources, an expunge of the cache
    ; is performed if it is less than half full. This is not always
    ; a suitable way of determining if an expunge of the cache
    ; should be per apc.smart allows you to set a runtime configuration
    ; value which is used to determine if an expunge should be run
    ; if (available_size < apc.smart * requested_size)
    ;apc.smart=0

    ; A "hint" about the number variables expected in the cache.
    ; Set to zero or omit if you are not sure;
    ;apc.entries_hint=4096

    ; The mktemp-style file_mask to pass to the mmap module
    apc.mmap_file_mask=/tmp/apc.XXXXXX

    ; 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 data at the same time.
    ; By default, APCu attempts to prevent "slamming" of a key.
    ; A key is considered "slammed" if it was the last key set,
    ; and a context other than the current one set it ( ie. it
    ; was set by another process or thread )
    ;apc.slam_defense=1

    ; Defines which serializer should be used
    ; Default is the standard PHP serializer.
    ;apc.serializer='default'

    ; use the SAPI request start time for TTL
    ;apc.use_request_time=1

    ; Enables APCu handling of signals, such as SIGSEGV, that write core files
    ; when signaled. APCu will attempt to unmap the shared memory segment in
    ; order to exclude it from the core file
    ;apc.coredump_unmap=0

    ; RFC1867 File Upload Progress hook handler
    ;apc.rfc1867=0
    ;apc.rfc1867_prefix =upload_
    ;apc.rfc1867_name=APC_UPLOAD_PROGRESS
    ;apc.rfc1867_freq=0
    ;apc.rfc1867_ttl=3600

    • Hi tom,

      Are looking user cache, opcode cache or both?

      With PHP 5.5, APCu is just user cache and PHP 5.5 have own module OPCache for opcode caching.

      I’m not upgrading this guide, because there is a lot of users using still PHP 5.4/5.3/5.2 with APC. but I have planned to write totally new guide to PHP 5.5 users.

  11. Thanks. I’m looking forward to it.

Add Comment Register



Leave a Comment

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackbacks/Pingbacks

  1. Install Apache/PHP 5.4.6 on Fedora 17/16, CentOS/RHEL 6.3/5.8 - [...] More info about PHP APC from PHP APC Configuration and Usage Tips and Tricks. [...]
  2. Install Nginx/PHP-FPM on Fedora 17/16, CentOS/RHEL 6.3/5.8 - [...] More info about PHP APC from PHP APC Configuration and Usage Tips and Tricks [...]

Pages: 1 2 3 4