Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check if a dir is empty whith php

Tags:

php

Is there a better way to check if a dir is empty than parsing it?

like image 980
Ced Avatar asked May 26 '11 08:05

Ced


People also ask

How can I tell if a directory is empty?

To check whether a directory is empty or not os. listdir() method is used. os. listdir() method of os module is used to get the list of all the files and directories in the specified directory.

What is dir () in PHP?

The dir() function returns an instance of the Directory class. This function is used to read a directory, which includes the following: The given directory is opened. The two properties handle and path of dir() are available. Both handle and path properties have three methods: read(), rewind(), and close()

How do you check if a file is in a directory PHP?

The file_exists() function accepts a filename and returns true if the file exists; otherwise it returns false . Note that the $filename can be also a path to a directory. In this case, the file_exists() function returns true if the directory exists.

Is PHP file empty?

PHP empty() FunctionThe empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true.


1 Answers

Don't think so. Shortest/quickest way I can think of is the following, which should work as far as I can see.

function dir_is_empty($path)
{
    $empty = true;
    $dir = opendir($path); 
    while($file = readdir($dir)) 
    {
        if($file != '.' && $file != '..')
        {
            $empty = false;
            break;
        }
    }
    closedir($dir);
    return $empty;
}

This should only go through a maximum of 3 files. The two . and .. and potentially whatever comes next. If something comes next, it's not empty, and if not, well then it's empty.

like image 143
Svish Avatar answered Sep 29 '22 00:09

Svish