How can I use PHP to check if a directory is empty?

I am using the following script to read a directory. If there is no file in the directory, it must be empty. The problem is that it simply says that the directory is empty, although there are files inside and vice versa.

<?php $pid = $_GET["prodref"]; $dir = '/assets/'.$pid.'/v'; $q = (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty'; if ($q=="Empty") echo "the folder is empty"; else echo "the folder is NOT empty"; ?> 
+71
directory php
Sep 21 2018-11-11T00: 00Z
source share
14 answers

It seems you need scandir instead of glob, since glob cannot see hidden unix files.

 <?php $pid = basename($_GET["prodref"]); //let sanitize it a bit $dir = "/assets/$pid/v"; if (is_dir_empty($dir)) { echo "the folder is empty"; }else{ echo "the folder is NOT empty"; } function is_dir_empty($dir) { if (!is_readable($dir)) return NULL; return (count(scandir($dir)) == 2); } ?> 

Note that this code is not the pinnacle of efficiency, since there is no need to read all the files just to indicate if the directory is empty. So the best version will be

 function dir_is_empty($dir) { $handle = opendir($dir); while (false !== ($entry = readdir($handle))) { if ($entry != "." && $entry != "..") { return FALSE; } } return TRUE; } 

By the way, do not use words to replace logical values. The very purpose of the latter is to tell you that something is empty or not.

 a === b 

the expression already returns Empty or Non Empty in terms of a programming language, FALSE or TRUE respectively - so that you can use the result itself in control structures such as IF() without any intermediate values

+120
Sep 21 '11 at 9:52
source share

I think using FilesystemIterator should be the fastest and easiest way:

 // PHP 5 >= 5.3.0 $iterator = new \FilesystemIterator($dir); $isDirEmpty = !$iterator->valid(); 

Or using access to a class member when instantiating:

 // PHP 5 >= 5.4.0 $isDirEmpty = !(new \FilesystemIterator($dir))->valid(); 

This works because the new FilesystemIterator will initially point to the first file in the folder - if there are no files in the folder, valid() will return false . (see the documentation here .)

As indicated by abdulmanov.ilmir, additionally check if the directory exists before using FileSystemIterator because otherwise it will throw an UnexpectedValueException .

+62
Sep 17 '13 at 18:08
source share

I found a quick solution

 <?php $dir = 'directory'; // dir path assign here echo (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty'; ?> 
+9
08 Oct
source share

use

 if ($q == "Empty") 

instead

 if ($q="Empty") 
+7
Sep 21 2018-11-11T00:
source share

Probably due to the assignment operator in the if .

Edit:

 if ($q="Empty") 

To:

 if ($q=="Empty") 
+4
Sep 21 2018-11-11T00:
source share

Try the following:

 <?php $dirPath = "Add your path here"; $destdir = $dirPath; $handle = opendir($destdir); $c = 0; while ($file = readdir($handle)&& $c<3) { $c++; } if ($c>2) { print "Not empty"; } else { print "Empty"; } ?> 
+4
Nov 22 '11 at 12:11
source share

This is a very old thread, but I thought I would give a dime. Other solutions did not help me.

Here is my solution:

 function is_dir_empty($dir) { foreach (new DirectoryIterator($dir) as $fileInfo) { if($fileInfo->isDot()) continue; return false; } return true; } 

Short and sweet. It works like a charm.

+4
Aug 13 '15 at 6:32
source share

For an object-oriented approach using the RecursiveDirectoryIterator from the Standard PHP Library (SPL) .

 <?php namespace My\Folder; use RecursiveDirectoryIterator; class FileHelper { /** * @param string $dir * @return bool */ public static function isEmpty($dir) { $di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS); return iterator_count($di) === 0; } } 

You do not need to make an instance of your FileHelper whenever you need it, you can access this static method wherever you need it:

 FileHelper::isEmpty($dir); 

The FileHelper class can be extended with other useful methods for copying, deleting, renaming, etc.

There is no need to verify the correctness of the directory inside the method, because if it is not valid, the RecursiveDirectoryIterator constructor will raise an UnexpectedValueException that covers this part sufficiently.

+4
Apr 12 '16 at 12:50
source share

@ Your general feeling

I think your example performers could be more efficient using strict comparisons:

 function is_dir_empty($dir) { if (!is_readable($dir)) return null; $handle = opendir($dir); while (false !== ($entry = readdir($handle))) { if ($entry !== '.' && $entry !== '..') { // <-- better use strict comparison here closedir($handle); // <-- always clean up! Close the directory stream return false; } } closedir($handle); // <-- always clean up! Close the directory stream return true; } 
+3
Aug 30 '13 at 8:11
source share

Just fix your code as follows:

 <?php $pid = $_GET["prodref"]; $dir = '/assets/'.$pid.'/v'; $q = count(glob("$dir/*")) == 0; if ($q) { echo "the folder is empty"; } else { echo "the folder is NOT empty"; } ?> 
+2
Sep 09 '13 at 9:48 on
source share

I use this method in my Wordpress CSV 2 POST plugin.

  public function does_folder_contain_file_type( $path, $extension ){ $all_files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path ) ); $html_files = new RegexIterator( $all_files, '/\.'.$extension.'/' ); foreach( $html_files as $file) { return true;// a file with $extension was found } return false;// no files with our extension found } 

It works with a specific extension, but can be easily modified to suit your needs, removing the “new RegexIterator value (“ string ”. Count $ all_files.

  public function does_folder_contain_file_type( $path, $extension ){ $all_files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path ) ); return count( $all_files ); } 
0
Aug 01 '14 at 16:37
source share

I had a similar problem recently, although the highest answer to the vote didn’t really work for me, so I had to come up with a similar solution. and again, this also may not be the most effective way to solve the problem,

I created such a function

 function is_empty_dir($dir) { if (is_dir($dir)) { $objects = scandir($dir); foreach ($objects as $object) { if ($object != "." && $object != "..") { if (filetype($dir."/".$object) == "dir") { return false; } else { return false; } } } reset($objects); return true; } 

and used it to check for an empty dricetory like this

 if(is_empty_dir($path)){ rmdir($path); } 
0
Aug 08 '15 at 11:22
source share

You can use this:

 function isEmptyDir($dir) { return (($files = @scandir($dir)) && count($files) <= 2); } 
0
Mar 06 '17 at 19:29
source share

First question: when is the directory empty? There are 2 files in the directory. as well as '..'.
Next to it on a Mac there may be a ".DS_Store" file. This file is created when any content is added to the directory. If these 3 files are in a directory, you can say that the directory is empty. Therefore, to check if the directory is empty (without testing if $ dir is a directory):

 function isDirEmpty( $dir ) { $count = 0; foreach (new DirectoryIterator( $dir ) as $fileInfo) { if ( $fileInfo->isDot() || $fileInfo->getBasename() == '.DS_Store' ) { continue; } $count++; } return ($count === 0); } 
0
Jun 08 '18 at 17:13
source share



All Articles