checking if a directory is empty

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
hame22
Forum Contributor
Posts: 214
Joined: Wed May 11, 2005 5:50 am

checking if a directory is empty

Post by hame22 »

Hi

I am attempting to do some validating when removing a directory using rmdir.

How can i validate whether or not a directory is empty of files?

thanks in advance
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: checking if a directory is empty

Post by Chris Corbyn »

hame22 wrote:Hi

I am attempting to do some validating when removing a directory using rmdir.

How can i validate whether or not a directory is empty of files?

thanks in advance
Assuming glob() finds hidden files....

Code: Select all

if (count(glob($dir.'/*')) > 2)
{
    //Directory is not empty
}
printf
Forum Contributor
Posts: 173
Joined: Wed Jan 12, 2005 5:24 pm

Post by printf »

On windows, none of the PHP functions can see hidden files or folders, you have to use CMD or the COM file scripting object to access that information to delete or change those so called permissions.

printf
hame22
Forum Contributor
Posts: 214
Joined: Wed May 11, 2005 5:50 am

Post by hame22 »

I have managed to solve the problem using the following code:

Code: Select all

if($checkDir = opendir($remove_dir)){
	$cFile = 0;
	 while($file = readdir($checkDir)){
           if($file != "." && $file != ".."){
               if(is_dir($dir . "/" . $file)){
                   $cFile++;
               }
               else{
                   $cFile++;
               }
           }
       }
	}
thanks alot for your suggestions
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

printf wrote:On windows, none of the PHP functions can see hidden files or folders, you have to use CMD or the COM file scripting object to access that information to delete or change those so called permissions.

printf
ahem:

Code: Select all

[feyd@home]>copy con hiddenfile.txt
hi
^Z
        1 file(s) copied.

[feyd@home]>attrib +h hiddenfile.txt

[feyd@home]>attrib hiddenfile.txt
A   H      C:\Web\tests\hiddenfile.txt

[feyd@home]>php -r "var_dump(glob('./*'));" | grep "hidden"
  string(16) "./hiddenfile.txt"

[feyd@home]>php -v
PHP 5.1.5 (cli) (built: Aug 15 2006 23:54:56)
Copyright (c) 1997-2006 The PHP Group
Zend Engine v2.1.0, Copyright (c) 1998-2006 Zend Technologies
    with Xdebug v2.0.0beta6, Copyright (c) 2002, 2003, 2004, 2005, 2006, by Derick Rethans
Post Reply