简体   繁体   中英

PHP, search and delete files from directory - performance

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

You may want to take a 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM