views:

112

answers:

2

Hi,

I want to delete cache files in a directory, the directory can contain up to 50.000 files. I currently I use this function.

// Deletes all files in $type directory that start with $start

    function clearCache($type,$start)
        {
        $open = opendir($GLOBALS['DOC_ROOT']."/cache/".$type."/");
        while( ($file = readdir($open)) !== false ) 
            {
            if ( strpos($file, $start)!==false ) 
                {
                unlink($GLOBALS['DOC_ROOT']."/cache/".$type."/".$file);
                }
            }
        closedir($open);        
        }

This works fine and it is fast, but is there any faster way to do this? (scan_dir seems to be slow). I can move the cache to memory obviously.

Thanks, hamlet

+1  A: 

You may want to look into the glob function, as it may be even faster... it depends on the C library's glob command to do its work.

I haven't tested this, but I think this would work::

foreach (glob("$GLOBALS['DOC_ROOT']."/cache/".$type."/".$start) as $file) {
    unlink($GLOBALS['DOC_ROOT']."/cache/".$type."/".$file);
}

Edit: I'm not sure if $file would be just the filename or the entire path. glob's documentation implies just the filename.

R. Bemrose
Looks good, first tests show that this is at least twice as fast. Thanks a lot!
hamlet
A: 

Either glob as suggested before or, if you can be certain there won't be malicious input, by issueing directly to the system via exec(sprintf('rm %s/sess*', realpath($path)));, which should be fastest.

Gordon