1

TLDR, i'm writing some code in PHP to count the total of my files and folder in the directory where my project is located at.

I have around 15.000 files and 1000 folder, but these queries took me arounds 6 seconds and 1 second for the pages, so in total i have to wait 6-8 seconds for the page to load and finish up.

Is there anyway to speed this up ? I have tried using array_column as per in this thread: PHP Foreach loop too slow when applied on large arrays

But still showing the same, still took 6 seconds.

Here's some of my code.

$files= 0;
$dir       = glob("../");
foreach ($dir as $obj) {                    
    if (is_dir($obj)) {
        $folders++;
        $scan = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($obj, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST);
        foreach ($scan as $file) {
            if (is_file($file)) {
                $files++;
                $exp = explode(".", $file);
                $exp2 = isset($exp[3]) ? $exp[3] : null;
                if ($exp2 == "txt") {
                    $files+;
                }

            } else {
                $folders++;
            }
        }
    } else {
        $files++;
    }
}
unset($exp2);

Where my $exp variable are consisting of 4 index.

array ( 
0 => '', 
1 => '', 
2 => '\\dashboard\\image37', 
3 => 'txt', )
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • 1
    Are you trying to print something on the screen, like showing all folders? – nice_dev Feb 28 '20 at 08:01
  • Ah yes, I try to print the counted result on the page. echo $files; – Rizaldy Putra Feb 28 '20 at 08:04
  • Why do you have RecursiveIteratorIterator() ? Are you printing all files in a directory? Are you showing a tree structure view on the browser? – nice_dev Feb 28 '20 at 08:19
  • Ah nope, i just counted the files from my root directory. for example, assumed that we used xampp. Then i put my project folder in /htdocs/project. Then what i tried is to count all of the files and folder in the htdocs. – Rizaldy Putra Feb 28 '20 at 08:29
  • 1
    Ok, for each of the 1000 folders you are counting how many files it has inside it? – nice_dev Feb 28 '20 at 08:33
  • 1
    Does this make counting simpler https://stackoverflow.com/questions/12801370/count-how-many-files-in-directory-php ? – nice_dev Feb 28 '20 at 08:34
  • Maybe you should [profile your code](https://stackoverflow.com/questions/21133/simplest-way-to-profile-a-php-script)? – Mawg says reinstate Monica Mar 09 '20 at 09:33

0 Answers0