Deleting Application Cache in Code Igniter with PHP

The Code Igniter documentation says:

Deleting Caches

If you no longer wish to cache a file you can remove the caching tag and it will no longer be refreshed when it expires. Note: Removing the tag will not delete the cache immediately. It will have to expire normally. If you need to remove it earlier you will need to manually delete it from your cache folder.

The CI_Output class ($this->output->cache(30)) doesn’t provide any public delete_cache() method. To delete database cache, you can use Code Igniter’s built in methods like $this->db->cache_delete_all(). For application cache, you need to write the code yourself.

Why would you want to?

There’re several use cases. For example, if a non-coder has just made a content update to your site via a CMS and you want to make sure it shows up immediately and not after the remaining amount of time specified via $this->output->cache(YOUR_TIME_INTERVAL).

Code snippet

Here’s one quick way to programmatically delete application cache in Code Igniter 2.1.3:

		if ($handle = opendir('YOUR_PATH_TO-application/cache')) {
		    //echo "Directory handle: $handle <br /><br/>";

		    while (false !== ($entry = readdir($handle))) 
		    {		        
		        //echo $entry."<br />";
		    	$n = basename($entry);
		    	//echo "name = ".$n."<br />";  
				//echo "length of name = ".strlen($n)."<br />";
				if( strlen($n) >= 32 ){
					//echo "file name's 32 chars long <br />";
					$p = APPPATH.'cache/'.$entry;
					//echo $p;					
					unlink($p);	
				}
				//echo "<br />";
		    }
		    closedir($handle);
		}    

Note: the //echo statements are just there for quick debugging, they shouldn’t be there in a real application.

Since Code Igniter’s application/cache directory contains only a few types of files and all of the non-cache files are named something like index.html or .htaccess, this quick approach looks for files whose names consist of 32 characters. The number is 32 because Code Igniter names cached content files using MD5 encryption.

This could potentially be slower than other ways of doing the same thing, since it involves a string manipulation method. I’m always interested in suggestions.