Reputation: 450
I have following code to count number of files in a folder using php
$x=0;
$filepath=$uplaod_drive."Workspace/12345";
$dir = new DirectoryIterator($filepath);
foreach($dir as $file ){
$x++;
}
But even if the folder is empty it show 3 files are there and if the folder has 8 files it show 11 files.
I would be very thankful if someone could explain this ..Thanks.
Upvotes: 0
Views: 587
Reputation: 1511
if you want to count only regular files:
$x=0;
$filepath=$uplaod_drive."Workspace/12345";
$dir = new DirectoryIterator($filepath);
foreach($dir as $file ){
if ($file->isFile()) $x++;
}
or if you want to skip the directories:
$x=0;
$filepath=$uplaod_drive."Workspace/12345";
$dir = new DirectoryIterator($filepath);
foreach($dir as $file ){
if (!$file->isDir()) $x++;
}
or if you want to skip the dot files:
$x=0;
$filepath=$uplaod_drive."Workspace/12345";
$dir = new DirectoryIterator($filepath);
foreach($dir as $file ){
if (!$file->isDot()) $x++;
}
Upvotes: 2
Reputation: 5306
The DirectoryIterator is counting the current directory (denoted by '.') and the previous directory (denoted by '..') as $files. Debug your code like so.
$x=0;
$filepath='C:\xampp\htdocs\\';
$dir = new DirectoryIterator($filepath);
foreach($dir as $file ){
echo $file . "<br/>";
$x++;
}
echo $x;
Then as mentioned in the comment above by @Prix you can skip if $file->isDot(), and if you dont want to count the directories then also skip if not $file->isFile().
$x=0;
$filepath='C:\xampp\htdocs\\';
$dir = new DirectoryIterator($filepath);
foreach($dir as $file ){
if ($file->isDot() || !$file->isFile()) continue;
//echo $file . "<br/>";
$x++;
}
echo $x;
Upvotes: 0