1

I want to check if a folder has at least 1 file. I am now using this to check if a folder is empty but this also checks if there is a subfolder in it.

if (count(glob($dir.'/*')) === 0 ) {}

And I only want to check for files in it

Kayathiri
  • 779
  • 1
  • 15
  • 26
Jack Maessen
  • 1,780
  • 4
  • 19
  • 51
  • use this solution and check for `3` instead of `2` : http://stackoverflow.com/a/7497848/2815635 – Niklesh Raut Jun 07 '16 at 09:33
  • Take a look at this question: http://stackoverflow.com/questions/7497733/how-can-use-php-to-check-if-a-directory-is-empty –  Jun 07 '16 at 09:34
  • @Rishi This is also not the right solution. When i have per example 5 subfolders in it but no file it says the folder is not empty! – Jack Maessen Jun 07 '16 at 09:43

1 Answers1

2

You can achieve it by using opendir and readdir

function check_file($dir) {
    $result = false;
    if($dh = opendir($dir)) {
        while(!$result && ($file = readdir($dh)) !== false) {
            $result = $file !== "." && $file !== ".." && !is_dir($file);
        }

        closedir($dh);
    }

    return $result;
}

$dir="/var/www/html/jkjkj/";// your path here
echo check_file($dir);// return 1 if file found otherwise empty
Saty
  • 22,443
  • 7
  • 33
  • 51