1

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?

Jack Maessen
  • 1,780
  • 4
  • 19
  • 51
  • does this help you: https://secure.php.net/manual/en/function.scandir.php#87527 ? And check if the array is `empty()`. –  Jun 07 '16 at 11:38
  • Possible duplicate of [PHP: How to list files in a directory without listing subdirectories](http://stackoverflow.com/questions/7684881/php-how-to-list-files-in-a-directory-without-listing-subdirectories) – Thamilhan Jun 07 '16 at 11:39

3 Answers3

3

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

kamp
  • 101
  • 7
3

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);
Cobra_Fast
  • 15,671
  • 8
  • 57
  • 102
1

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; 
?>
Manjeet Barnala
  • 2,975
  • 1
  • 10
  • 20