Reputation: 1864
I want to check if a folder contains at least 1 real file. I tried this code:
$dir = "/dir/you/want/to/scan";
$handle = opendir($dir);
$folders = 0;
$files = 0;
while(false !== ($filename = readdir($handle))){
if(($filename != '.') && ($filename != '..')){
if(is_dir($filename)){
$folders++;
} else {
$files++;
}
}
}
echo 'Number of folders: '.$folders;
echo '<br />';
echo 'Number of files: '.$files;
when in folder scan
are 1 subfolder and 2 real files; the code above gives me as output:
Number of folders: 0
Number of files: 3
So it seems that a subfolder is seen as a file. But i want only real files to be checked. How can i achieve that?
Upvotes: 1
Views: 2279
Reputation: 2995
You can use scandir
scandir — List files and directories inside the specified path
<?php
$dir = "../test";
$handle = scandir($dir);
$folders = 0;
$files = 0;
foreach($handle as $filename)
{
if(($filename != '.') && ($filename != '..'))
{
if(is_dir($filename))
{
$folders++;
}
else
{
$files++;
}
}
}
echo 'Number of folders: '.$folders;
echo '<br />';
echo 'Number of files: '.$files;
?>
Upvotes: 1
Reputation: 16071
You can do this job easily using glob()
:
$dir = "/dir/you/want/to/scan";
$folders = glob($dir . '/*', GLOB_ONLYDIR);
$files = array_filter(glob($dir . '/*'), 'is_file');
echo 'Number of folders: ' . count($folders);
echo '<br />';
echo 'Number of files: ' . count($files);
Upvotes: 3
Reputation: 101
based on your first line, where you specify a path, which is different to your scripts path, you should combine $dir and the $filename in the is_dir if-clause.
Why?
Because if your script is on:
/var/web/www/script.php
and you check the $dir:
/etc/httpd
which contains the subfolder "conf", your script will check for the subfolder /var/web/www/conf
Upvotes: 3