"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > ## How to Reliably Determine if a Directory is Empty in PHP?

## How to Reliably Determine if a Directory is Empty in PHP?

Published on 2024-11-08
Browse:539

## How to Reliably Determine if a Directory is Empty in PHP?

Verifying Directory Emptiness in PHP

Determining whether a directory is empty can be a vital task in various web development scenarios. However, certain scripts may encounter issues where the output incorrectly suggests an empty or non-empty directory despite the presence or absence of files within.

Original Script

The provided script attempts to check for directory emptiness using the following code:

$q = (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';

However, the glob() function may fail to detect Unix hidden files, leading to inaccurate results.

Improved Solution

To resolve this issue, we recommend using the scandir() function instead of glob(), as it can detect both regular and hidden files. Additionally, to improve efficiency, we can use a custom function to check for emptiness more quickly:

function is_dir_empty($dir) {
  return (count(scandir($dir)) == 2);
}

This function checks if the directory contains only two entries: the current directory (".") and the parent directory (".."), indicating an empty directory.

Best Practice

As a best practice, it is advisable to use boolean values directly in control structures rather than relying on text strings like "Empty" or "Not empty." Boolean expressions provide a more concise and accurate way to determine empty or non-empty conditions.

For instance, instead of using:

if ($q == "Empty") {
  // ...
}

You can directly use:

if (is_dir_empty($dir)) {
  // ...
}
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3