Home > Article > Backend Development > How to Count Files in a Directory Using PHP?
Counting Files in a Directory Using PHP
In your project, you're looking to determine the number of files within a specific directory. Let's delve into how to achieve this using PHP.
The code you initially provided iterates through a directory using the readdir() function. However, it doesn't account for hidden files or subdirectories. To address this, you can use the following refined approach:
<code class="php">$dir = opendir('uploads/'); # Directory to count files from $i = 0; # Initialize counter $excludedFiles = ['.', '..']; # Ignore these files # Iterate through the directory while (false !== ($file = readdir($dir))) { if (!in_array($file, $excludedFiles) && !is_dir($file)) { $i++; } } closedir($dir); echo "There were $i files"; # Output the count</code>
By excluding hidden files (beginning with ".") and subdirectories (determined by is_dir()), this revised code accurately counts only regular files within the specified directory.
Alternatively, you can use a more concise approach based on FilesystemIterator:
<code class="php">$fi = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS); printf("There were %d Files", iterator_count($fi));</code>
Here, the FilesystemIterator class skips hidden files (.) and parent directories (..), making it a straightforward solution for counting files. Both methods provide accurate and efficient counting of files within a directory, depending on your preference.
The above is the detailed content of How to Count Files in a Directory Using PHP?. For more information, please follow other related articles on the PHP Chinese website!