Counting Files in a Directory: PHP and Beyond
Counting files within a specific directory is a common requirement, whether you are archiving logs, cleaning up temporary uploads, or simply auditing your storage quota. The standard approach in legacy PHP relies on the opendir() and readdir() functions. However, the implementation often contains subtle logical errors that prevent it from working as intended.
Consider this snippet attempting to count files in an uploads/ directory:
$dir = opendir('uploads/');
$i = 0;
while (false !== ($file = readdir($dir))) {
if (!in_array($file, array('.', '..') and !is_dir($file)) $i++;
}
echo "There were $i files";
closedir($dir); // Essential cleanup
This code fails on two fronts: operator precedence and logic flow. The condition !in_array(...) is wrapped around a bitwise AND (and) instead of a logical OR combined with the directory check. Furthermore, in_array returns a boolean, but the syntax implies an attempt to negate a single condition incorrectly. If you run this, $i will likely remain zero because the logic never evaluates correctly, and the script may even throw a warning regarding and usage in complex expressions.
Correcting the Logic with Legacy Functions
To fix the legacy approach, you must explicitly check the file type before incrementing the counter. The directory entries always include . (current) and .. (parent), so these must be excluded regardless of their type.
Here is the corrected version using procedural functions:
$dir = opendir('uploads/');
$count = 0;
if ($dir !== false) {
while (($file = readdir($dir)) !== false) {
// Skip hidden entries and directories
if ($file === '.' || $file === '..') {
continue;
}
if (!is_dir($file)) {
$count++;
}
}
closedir($dir);
}
echo "There were $count files";
This structure is safer because it separates the exclusion logic (continue) from the inclusion check. It ensures that subdirectories are not counted as regular files, which is often a source of bugs when calculating actual file counts versus directory depth.
The Modern Standard: scandir()
While procedural functions work, they are verbose and prone to the syntax errors seen above. A more robust alternative is scandir(). This function returns an array of filenames in the directory, sorted alphabetically by default. It simplifies iteration significantly.
$dir = 'uploads/';
$count = 0;
if (($files = scandir($dir)) !== false) {
foreach ($files as $file) {
if ($file !== '.' && $file !== '..' && !is_dir($file . DIRECTORY_SEPARATOR)) {
// Note: is_dir() behavior can vary slightly depending on how the path is constructed.
// It is safer to use scandir with SCANDIR_SORT_NONE and check against a full path.
}
}
}
A critical nuance with scandir() is that it returns filenames without directory prefixes, but passing them back to is_dir() works correctly if the base directory exists. However, for complex filtering needs (like counting only .php files), glob() combined with filetype checks or scandir with flags provides more flexibility without opening and closing handles manually.
Performance Considerations: Why Not count(glob(...))?
Developers often reach for count(glob('uploads/*')). While concise, this method is inefficient for large directories because it loads every filename into memory at once before filtering. If your uploads/ folder contains thousands of files, glob() might hit memory limits or cause significant latency compared to streaming through opendir() or scandir(). Additionally, glob does not naturally distinguish between files and directories without an extra check inside the loop, making it less precise for strict file counting tasks.
Integration in Modern Frameworks
If you are building this logic within a modern PHP application using Symfony or Laravel, avoid writing raw filesystem code unless necessary. These frameworks provide abstractions that handle permission checks and path resolution automatically.
In Laravel, for instance, the Storage facade allows you to interact with directories safely, often mounted on local disks or S3. You would typically use the file system interface provided by the framework rather than direct PHP commands, ensuring consistency across environments:
use Illuminate\Support\Facades\Storage;
$count = Storage::disk('public')->allFiles('uploads')->count();
// This counts only files, ignoring subdirectories automatically if using allFiles()
// on a specific path structure, though path logic varies by version.
For raw PHP scripts outside of frameworks, stick to the corrected opendir loop or switch to scandir() for cleaner syntax. Always remember to close the directory handle with closedir() to release system resources, especially in long-running processes like daemons or scheduled tasks.
