[php] How to clear APC cache entries?

I need to clear all APC cache entries when I deploy a new version of the site. APC.php has a button for clearing all opcode caches, but I don't see buttons for clearing all User Entries, or all System Entries, or all Per-Directory Entries.

Is it possible to clear all cache entries via the command-line, or some other way?

This question is related to php performance caching apc

The answer is


This is not stated in the documentation, but to clear the opcode cache you must do:

apc_clear_cache('opcode');

EDIT: This seems to only apply to some older versions of APC..

No matter what version you are using you can't clear mod_php or fastcgi APC cache from a php cli script since the cli script will run from a different process as mod_php or fastcgi. You must call apc_clear_cache() from within the process (or child process) which you want to clear the cache for. Using curl to run a simple php script is one such approach.


I don't believe any of these answers actually work for clearing the APC cache from the command line. As Frank Farmer commented above, the CLI runs in a process separate from Apache.

My solution for clearing from the command line was to write a script that copies an APC clearing script to the web directory and accesses it and then deletes it. The script is restricted to being accessed from the localhost.

  1. apc_clear.php

    This is the file that the script copies to the web directory, accesses, and deletes.

    <?php
    if (in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1')))
    {
      apc_clear_cache();
      apc_clear_cache('user');
      apc_clear_cache('opcode');
      echo json_encode(array('success' => true));
    }
    else
    {
      die('SUPER TOP SECRET');
    }
    
  2. Cache clearing script

    This script copies apc_clear.php to the web directory, accesses it, then deletes it. This is based off of a Symfony task. In the Symfony version, calls are made to the Symfony form of copy and unlink, which handle errors. You may want to add checks that they succeed.

    copy($apcPaths['data'], $apcPaths['web']); //'data' is a non web accessable directory
    
    $url = 'http://localhost/apc_clear.php'; //use domain name as necessary
    $result = json_decode(file_get_contents($url));
    
    if (isset($result['success']) && $result['success'])
    {
      //handle success
    }
    else
    {
      //handle failure
    }
    
    unlink($apcPaths['web']);
    

If you are running on an NGINX / PHP-FPM stack, your best bet is to probably just reload php-fpm

service php-fpm reload (or whatever your reload command may be on your system)


if you run fpm under ubuntu, need to run the code below (checked on 12 and 14)

service php5-fpm reload

Another possibility for command-line usage, not yet mentioned, is to use curl.

This doesn't solve your problem for all cache entries if you're using the stock apc.php script, but it could call an adapted script or another one you've put in place.

This clears the opcode cache:

curl --user apc:$PASSWORD "http://www.example.com/apc.php?CC=1&OB=1&`date +%s`"

Change the OB parameter to 3 to clear the user cache:

curl --user apc:$PASSWORD "http://www.example.com/apc.php?CC=1&OB=3&`date +%s`"

Put both lines in a script and call it with $PASSWORD in your env.


As defined in APC Document:

To clear the cache run:

php -r 'function_exists("apc_clear_cache") ? apc_clear_cache() : null;'

apc.ini

apc.stat = "1" will force APC to stat (check) the script on each request to determine if it has been modified. If it has been modified it will recompile and cache the new version.

If this setting is off, APC will not check, which usually means that to force APC to recheck files, the web server will have to be restarted or the cache will have to be manually cleared. Note that FastCGI web server configurations may not clear the cache on restart. On a production server where the script files rarely change, a significant performance boost can be achieved by disabled stats.


apc_clear_cache() only works on the same php SAPI that you want you cache cleared. If you have PHP-FPM and want to clear apc cache, you have do do it through one of php scripts, NOT the command line, because the two caches are separated.

I have written CacheTool, a command line tool that solves exactly this problem and with one command you can clear your PHP-FPM APC cache from the commandline (it connects to php-fpm for you, and executes apc functions)

It also works for opcache.

See how it works here: http://gordalina.github.io/cachetool/


I know it's not for everyone but: why not to do a graceful Apache restart?

For e.g. in case of Centos/RedHat Linux:

sudo service httpd graceful

Ubuntu:

sudo service apache2 graceful

If you want to monitor the results via json, you can use this kind of script:

<?php

$result1 = apc_clear_cache();
$result2 = apc_clear_cache('user');
$result3 = apc_clear_cache('opcode');
$infos = apc_cache_info();
$infos['apc_clear_cache'] = $result1;
$infos["apc_clear_cache('user')"] = $result2;
$infos["apc_clear_cache('opcode')"] = $result3;
$infos["success"] = $result1 && $result2 && $result3;
header('Content-type: application/json');
echo json_encode($infos);

As mentioned in other answers, this script will have to be called via http or curl and you will have to be secured if it is exposed in the web root of your application. (by ip, token...)


My work-around for Symfony build having loot of instances at the same server:

Step 1. Create trigger or something to set a file flag (eg. Symfony command) then create marker file ..

file_put_contents('clearAPCU','yes sir i can buggy')

Step 2. On index file at start add clearing code and remove marker file.

if(file_exists('clearAPCU')){
    apcu_clear_cache();
    unlink('clearAPCU');
}

Step 2. Run app.


We had a problem with APC and symlinks to symlinks to files -- it seems to ignore changes in files itself. Somehow performing touch on the file itself helped. I can not tell what's the difference between modifing a file and touching it, but somehow it was necessary...


A good solution for me was to simply not using the outdated user cache any more after deploy.

If you add prefix to each of you keys you can change the prefix on changing the data structure of cache entries. This will help you to get the following behavior on deploy:

  1. Don't use outdated cache entries after deploy of only updated structures
  2. Don't clean the whole cache on deploy to not slow down your page
  3. Some old cached entries can be reused after reverting your deploy (If the entries wasn't automatically removed already)
  4. APC will remove old cache entries after expire OR on missing cache space

This is possible for user cache only.


New APC Admin interface have options to add/clear user cache and opcode cache, One interesting functionality is to add/refresh/delete directory's from opCode Cache

APC Admin Documentation

enter image description here


Create APC.php file

foreach(array('user','opcode','') as $v ){
    apc_clear_cache($v);
}

Run it from your browser.


The stable of APC is having option to clear a cache in its interface itself. To clear those entries you must login to apc interface.

APC is having option to set username and password in apc.php file.

enter image description here


If you want to clear apc cache in command : (use sudo if you need it)

APCu

php -r "apcu_clear_cache();" 

APC

php -r "apc_clear_cache(); apc_clear_cache('user'); apc_clear_cache('opcode');"

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to performance

Why is 2 * (i * i) faster than 2 * i * i in Java? What is the difference between spark.sql.shuffle.partitions and spark.default.parallelism? How to check if a key exists in Json Object and get its value Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly? Most efficient way to map function over numpy array The most efficient way to remove first N elements in a list? Fastest way to get the first n elements of a List into an Array Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3? pandas loc vs. iloc vs. at vs. iat? Android Recyclerview vs ListView with Viewholder

Examples related to caching

Disable nginx cache for JavaScript files How to prevent Browser cache on Angular 2 site? Curl command without using cache Notepad++ cached files location Laravel 5 Clear Views Cache Write-back vs Write-Through caching? Tomcat 8 throwing - org.apache.catalina.webresources.Cache.getResource Unable to add the resource Chrome - ERR_CACHE_MISS How do I use disk caching in Picasso? How to clear gradle cache?

Examples related to apc

How to disable XDebug What is causing "Unable to allocate memory for pool" in PHP? apc vs eaccelerator vs xcache How to clear APC cache entries?