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