Codeigniter – Too many files in cache directory

Codeigniter file-based caching will take the completely rendered output and save it to the disk. So there is no need to talk to the database or process anything and it is tremendously reducing the server load.

But, It is limited if we have more than 10k files( depends upon server configuration ) in cache directory.

I had this problem. So, In the cache I had more than 10.000 files, and that probably influence the performance of reading.

To resolve that I added these lines of code.
That split cache files in multiple sub-directories.

Open the file – system/core/output.php – function _write_cache

$uri = $CI->config->item('base_url').
$CI->config->item('index_page').
$CI->uri->uri_string();


//cache in sub-directory
$md5 = md5($uri);
$cache_path.= substr($md5, 0,1).'/';
if ( ! is_dir($cache_path)){
mkdir($cache_path);
}
$cache_path.=$md5;
// end cache in subdirectory

if ( ! $fp = @fopen($cache_path, FOPEN_WRITE_CREATE_DESTRUCTIVE))
{
log_message('error', "Unable to write cache file: ".$cache_path);
return;
}

In system/core/output.php – function _display_cache

if ( ! is_dir($cache_path) OR ! is_really_writable($cache_path))
{
return FALSE;
}

// Chalda here: cache in subdirectory
$md5 = md5($uri);
$cache_path.= substr($md5, 0,1).'/';
if ( ! is_dir($cache_path)){
return FALSE;
}
// end cache in subdirectory

$filepath = $cache_path.md5($uri);
So now it divides the cache into sub-folders according to the first character of the md5’s file.

cache directory before the change

cachedir/007dcd4f736e9be08adbe71f15e87bd9
cachedir/aee5f9543140bee532d3fe5e9b990e38
cachedir/a8cc3229af15a6259c33a5302884409f
cachedir/c5615a9a01e68d34682b2f7185bf5437

cache directory after the change

cachedir/0/007dcd4f736e9be08adbe71f15e87bd9
cachedir/a/aee5f9543140bee532d3fe5e9b990e38
cachedir/a/a8cc3229af15a6259c33a5302884409f
cachedir/c/c5615a9a01e68d34682b2f7185bf5437

The above change is for one level sub-directory only. If you want more level, then just change the “substr” level.

Eg:

Instead:
$cache_path.= substr($md5, 0,1).’/'; // for single level
Like:
$cache_path.= substr($md5, 0,3).’/'; // for three levels.

Leave a Reply

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>