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.
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.
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>
Use php DirectoryIterator or FileSystemIterator:
$directory = new DirectoryIterator(__DIR__);
$num = 0;
foreach ($directory as $fileinfo) {
if ($fileinfo->isFile()) {
if($fileinfo->getExtension() == 'txt')
$num++;
}
}
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') );
This is a very simple code that works well. :)
$files = glob('yourfolder/*.{txt}', GLOB_BRACE);
foreach($files as $file) {
your work
}