Drupal: How to Clear the Cache via PHP

Most Drupal sites are configured to cache pages (and blocks) to improve performance.  Normally, if you're having a problem, you should use the admin pages to clear the cache:

Configuration -> Development -> Performance -> Clear all caches

However, if you've had theme (or other) problems with your site, you may be unable to access your admin pages.  Even if you correct the underlying problem, you may not see any improvement to your site since your pages are still cached.  Often, you may need to clear the cache to even see if you've fixed the problem.

If you are unable to access your admin pages, but can still access your drupal files, an easy way to clear the cache is to use the PHP function:

drupal_flush_all_caches();

Once you know the function, there are any number of ways to invoke it.  But take care that you do not end up calling this on every page load!

A quick and easy way I have used to call this function is as follows:

  • create a copy of the main site index page 'index.php', and call it 'flush.php'.
  • modify 'flush.php' to call the above function.

Here's what it looks like before and after.  When you first create 'flush.php' it looks like:

define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler();

Remove the last line and replace it with the 'drupal_flush_all_caches' function so it looks like:

define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
drupal_flush_all_caches();

Now, while you're fixing the problems with your site, you can flush the cache at any time by calling:

http://your-domain-name/your-site-dir/flush.php

Don't forget to delete 'flush.php' after you're done troubleshooting!

I hope this helps someone!