172

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?

lo_fye
  • 6,790
  • 4
  • 33
  • 49
  • 1
    i'd be interested in how to clear expired entries! you can specify a ttl, but php.net doc says it is expunged upon the next request when it has expired... – The Surrican Aug 26 '10 at 23:14

19 Answers19

146

You can use the PHP function apc_clear_cache.

Calling apc_clear_cache() will clear the system cache and calling apc_clear_cache('user') will clear the user cache.

Travis Beale
  • 5,534
  • 7
  • 34
  • 34
  • 20
    I discovered that to do this via command-line you need to go into apc.ini and set: apc.enable_cli=1 – lo_fye May 26 '09 at 15:42
  • 51
    lo_fye: Does that actually work? In my experience, I found that APC CLI was totally separate from apache's APC cache -- and rightfully so, since any CLI process runs in a completely separate process from Apache. – Frank Farmer May 26 '09 at 18:59
  • 9
    Frank Farmer: I confirm this does work with either Apache or Nginx running PHP 5.3.10 and the PHP-FPM interface. I created a shell script that executes this command `php -r "apc_clear_cache();"` – ezraspectre Jul 05 '12 at 11:00
  • 13
    This does NOT work if you run PHP using mod_php. For the reason Frank Farmer stated. – David Nov 28 '12 at 15:33
  • 11
    I run Ubuntu Server 12.04 with Nginx and PHP-FPM with PHP version 5.4. apc_clear_cache() and apc_clear_cache('user') on the command line do NOT clear the APC cache of the webserver / webpages!!! – Pieter Vogelaar May 08 '13 at 12:24
  • The solution I'm using for this is to have the CLI PHP script make an HTTP request to localhost to a PHP script that just runs `apc_clear_cache` (see jeremy's answer below for implmentation). – Fredrick Brennan Jul 22 '14 at 13:12
118

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']);
    
Community
  • 1
  • 1
Jeremy Kauffman
  • 10,293
  • 5
  • 42
  • 52
  • 8
    You can also just restart the server, e.g. Apache if you're using mod_php or PHP FPM if you're using that. Your solution is more elegant (no server restart required) but more complex :) – El Yobo Jun 16 '12 at 00:57
  • 5
    This is nicer than restarting php-fpm/apache because it doesn't require your deploy user to have sudo access. If you are deploying to multiple servers, typing in the sudo password for each could get tiresome. – andrew Jul 24 '12 at 22:27
  • Personally I don't mind typing the sudo password (my deployment script saves the password). But I'd like to avoid downtime as much as possible, that's why I'm interested in flushing APC files. For Nginx there's a (not-so-easy) way to restart without any downtime. I don't know for PGPfcgi, but I don't think so. Does flushing APC cause downtime ? – Julien Dec 19 '12 at 09:03
  • @andrew You can configure your user to use sudo without typing your password. Though if clearing APC is all it takes, that's indeed better, like Julien said. – ChocoDeveloper Feb 04 '13 at 10:38
  • 1
    @Julien I guess it may increase server load if you are storing cpu intensive results or something. I wouldn't do it on a peak hour. – ChocoDeveloper Feb 04 '13 at 10:40
  • @ChocoDeveloper at that point you might as well run everything off of root. It can be extremely convenient to have passwordless sudo, but the security implications are too great for me to consider doing this on any server in a production environment. – andrew Feb 04 '13 at 18:06
  • @andrew What security implications? You still have to authenticate. Also, you are still protected from mistakenly deleting everything with 'rm -r something' or any other thing that requires special permissions, since you still have to preppend it with 'sudo'. It is in no way the same as running everything as root. – ChocoDeveloper Feb 05 '13 at 06:16
  • @ChocoDeveloper the problem is that if there is a vulnerability in your PHP script, the attacker can use sudo to put backdoors into your system and potentially hide their tracks by changing logfiles etc. If the user doesn't have passwordless sudo, the attacker still needs either the root password or the user's password, so the machine is a lot safer. (Admittedly this assumes you run the PHP scripts with the same user that deploys them, which doesn't have to be the case) – rjmunro Dec 04 '13 at 11:47
69

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
Tadas Sasnauskas
  • 2,183
  • 1
  • 22
  • 24
  • 4
    I know this isn't ideal, but I'm glad you mentioned this for a quick and dirty solution. – Bryan Petty Dec 30 '11 at 18:06
  • 1
    Sorry for re-opening this thread but I'm faced with the same issue and I'm wondering why isn't a cronjob making a graceful apache2 restart ideal? What are some of the downsides to this approach? – user2028856 Jan 04 '14 at 17:44
  • @user2028856 There's nothing wrong with it except some might not always have full control of the server. So if it works for you - use it. – Tadas Sasnauskas Jan 05 '14 at 23:53
  • @TadasSasnauskas What do you mean by "not always have full control of the server."? I mean will running it every half an hour or so cause apache to crash or break some other running actions such as a cron backup? – user2028856 Jan 06 '14 at 17:24
  • @user2028856 I meant that some might host their sites on shared server without capability to restart web server. Running graceful restart every 30min should be fine given you do not run background workers via cli with apc enabled (long story short: in some cases can cause kernel panic) – Tadas Sasnauskas Jan 07 '14 at 15:18
  • In cases where you have multiple storages, for example cli and webserver, this is the one and only solution. – dabito May 13 '14 at 19:00
  • APC caches your php code, you shouldn't clear the cache every 30min because APC will be useless :). You should only clear the APC cache when you have code changes. – ProtheanTom Oct 12 '14 at 14:24
27

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.

ColinM
  • 13,367
  • 3
  • 42
  • 49
  • 1
    I should add, if you are running mod_php and want to clear the cache via cli-mode php, you can't really do this since the two are running in different environments. My solution was to have the cli mode php call itself over http using file_get_contents. Ugly, but it works. – ColinM Oct 06 '10 at 20:40
  • Pipe'ing a dump of a valid fastcgi request directly to php-fpm with netcat works without having to install a real http server, since the php-fpm server might be separate from the http one – baloo Nov 17 '11 at 15:32
  • This answer is wrong. Like it is explained in the documentation the opcode cache is always cleared if the given parameter is != 'user'. – stollr Nov 12 '13 at 09:36
  • @naitsirch Perhaps this was a bug that is fixed in the latest version.. At the time I posted the answer this is what worked for me. Unfortunately I don't know what version I was using at the time but this answer is apparently useful to 25 other people who were ostensibly using the same version I was.. Documentation is not always correct and is definitely not always correct for older versions. – ColinM Dec 11 '13 at 17:35
12

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)

passion4code
  • 133
  • 1
  • 4
  • service php5-fpm reload is what make it work I checked apc.php status file and cache status was reset I was need this after add option apc.stat=0 to php.ini – Salem Dec 13 '14 at 11:20
12

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');"
Léo Benoist
  • 2,511
  • 1
  • 20
  • 18
  • I am getting error on my terminal like that please help me "PHP Fatal error: Call to undefined function apc_clear_cache() in Command line code on line 1" – RaviPatidar Aug 22 '15 at 06:56
  • 1
    You should test of your apc is properly installed with "php -m | grep apc" – Léo Benoist Aug 24 '15 at 07:26
5

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/

4

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.

Andy Triggs
  • 1,286
  • 12
  • 17
4

As defined in APC Document:

To clear the cache run:

php -r 'function_exists("apc_clear_cache") ? apc_clear_cache() : null;'
codersofthedark
  • 9,183
  • 8
  • 45
  • 70
4

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...)

COil
  • 7,201
  • 2
  • 50
  • 98
3

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

service php5-fpm reload
hrnsky
  • 111
  • 2
  • 6
1

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

vinothvetrivel
  • 109
  • 3
  • 10
1

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.

mal
  • 1,755
  • 13
  • 12
1

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

Jithin Jose
  • 1,761
  • 2
  • 19
  • 35
0

Create APC.php file

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

Run it from your browser.

anshuman
  • 3,496
  • 1
  • 19
  • 13
  • 2
    As far as I understand, the CLI instance will not share the same APC cache memory segment, so this will do nothing but clear an empty, isolated APC cache segment. – A.B. Carroll Jan 08 '13 at 18:24
  • depending on distros & configurations APC cache may have separate memory segment, I have it updated for more generic solution. – anshuman Mar 27 '13 at 09:34
0

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.

mabe.berlin
  • 1,043
  • 7
  • 22
0

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.

0

TL;DR: delete cache files at /storage/framework/cache/data/

I enabled APC but it wasn't installed (and also couldn't be installed), so it threw Call to undefined function Illuminate\Cache\apc_store().

"Ok, I'd just disable it and it should work".

Well, nope. Then I got stuck with Call to undefined function Illuminate\Cache\apc_delete()

chonz0
  • 371
  • 2
  • 5
-1

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...