4

I'm working on an IMDB style website and I need to dynamically find the amount of reviews for a movie. The reviews are stored in a folder called /moviefiles/moviename/review[*].txt where the [*] is the number that the review is. Basically I need to return as an integer how many of those files exist in that directory. How do I do this?

Thanks.

LF00
  • 27,015
  • 29
  • 156
  • 295
Dakota Wagner
  • 117
  • 2
  • 15

5 Answers5

3

Use php DirectoryIterator or FileSystemIterator:

$directory = new DirectoryIterator(__DIR__);
$num = 0;
foreach ($directory as $fileinfo) {
    if ($fileinfo->isFile()) {
        if($fileinfo->getExtension() == 'txt')
            $num++;
    }
}
LF00
  • 27,015
  • 29
  • 156
  • 295
  • Nice to see somebody using [DirectoryIterator()](http://php.net/manual/en/class.directoryiterator.php). This kind of task is exactly why that iterator exists. – Abela Jul 19 '18 at 23:09
1

Take a look at the glob() function: http://php.net/manual/de/function.glob.php
You can then use sizeof() to count how many files there are.

petroni
  • 766
  • 1
  • 13
  • 29
1

First, use glob () to get file list array, then use count () to get array length, the array length is file count.

Simplify code:

$txtFileCount = count( glob('/moviefiles/moviename/review*.txt') );
Calos
  • 1,783
  • 19
  • 28
0

You can use this php code to get the number of text files in a folder

<div id="header">
<?php 
    // integer starts at 0 before counting
    $i = 0; 
    $dir = 'folder-path';
    if ($handle = opendir($dir)) {
        while (($file = readdir($handle)) !== false){
            if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) 
            {
                $temp = explode(".",$file);
                if($temp[1]=="txt")
                    $i++;
            }
        }
    }
    // prints out how many were in the directory
    echo "There were $i files";
?>
</div>
sujivasagam
  • 1,659
  • 1
  • 14
  • 26
0

This is a very simple code that works well. :)

$files = glob('yourfolder/*.{txt}', GLOB_BRACE);
foreach($files as $file) {
    your work
}
Petey Howell
  • 190
  • 14