Search code examples
phpfunctionfilesize

PHP is_dir function is too slow when comparing many large files


I have a directory with over 600 mp4 files in it and a few directories. I am trying to loop through the files and determine if the file is a directory or not and get the filesize. The problem is that is_dir and filesize take WAY to long when getting this info for large files (>2GB). Is there an efficient way to do this? in my example code I have commented out filesize and is_dir and then I get the array back in a few seconds. Otherwise it takes forever.

    $files=array();
    $directory=opendir($dir);
    while ($file = readdir($directory)) {
        if($file != "." && $file != ".." && $file != '$RECYCLE.BIN'){
                $rec=array(
                    'afile'=>"{$dir}/{$file}",
                    'name'=>$file
                );
                //if(is_dir($rec['afile'])){$rec['type']='dir';}
                //else{$rec['type']='file';}
                //$rec['size']=filesize($rec['afile']);
                $files[]=$rec;
            }
        }
    closedir($directory);

Solution

  • I had the same need as you and solved it with a workaround.

    Instead of checking if $file is a directory, I checked if the file $file.'\..' exists.

    This second approach is much faster (empirical testing at least).

    So your code can be rewritten like this:

    $files = array();
    $directory = opendir($dir);
    while ($file = readdir($directory))
    {
        if($file != "." && $file != ".." && $file != '$RECYCLE.BIN' && file_exists($directory.'\\'.$file.'\\..') )
        {
            // do things...
        }
    }
    closedir($directory);