PHP, finding and deleting files from a directory - performance

I want to delete cache files in a directory, a directory can contain up to 50,000 files. I am currently using this feature.

// 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's fast, but is there a faster way to do this? (scan_dir seems slow). I can explicitly move the cache to memory.

Thank you, Village

+4
source share
2 answers

You can take a look at the glob function, as it can be even faster ... it depends on the glob C library to do its job.

I have not tested this, but I think it 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 will be just the file name or the whole way. The glob documentation only implies a file name.

+4
source

Either glob , as suggested earlier, or if you can be sure that there will be no malicious input by sending directly to the system via exec(sprintf('rm %s/sess*', realpath($path))); which should be the fastest.

0
source

All Articles