Scanning Directories in PHP: Beyond scandir()
Reading a list of files from a folder is a fundamental operation when building web applications, whether you are generating a file manager interface, building a CMS backend, or processing uploaded assets. While the question often arises for its simplicityâhow do I get that array of filenames?âthe answer requires careful consideration of how PHP handles filesystem objects and how your application context interacts with them.
The most straightforward approach for legacy PHP scripts involves using scandir(). This function returns an array of file and directory names based on the path you provide. However, relying solely on the raw string output from scandir() can lead to subtle bugs, particularly regarding hidden files and relative paths. If you pass a simple string like "uploads/", PHP resolves it relative to the current working directory, which might not match your application's root. For robust applications, especially those running behind web servers like Apache or Nginx, you often need to resolve an absolute path first using realpath(). This ensures that whether the script is invoked via CLI or HTTP, you are scanning the exact same physical location on the disk.
Here is a practical pattern for safely retrieving a list of files while excluding directories and hidden entries:
$folderPath = '/var/www/html/assets'; // Use absolute paths in production
$absolutePath = realpath($folderPath);
if ($absolutePath === false) {
throw new Exception("Directory does not exist or is not accessible");
}
$files = [];
$items = scandir($absolutePath);
foreach ($items as $item) {
// Skip . and .. which are automatically returned by scandir
if ($item === '.' || $item === '..') {
continue;
}
// Check the actual path to ensure it's a file, not a directory
$fullPath = realpath($folderPath . '/' . $item);
if ($fullPath && is_file($fullPath)) {
$files[] = basename($fullPath);
}
}
This implementation adds a layer of safety by verifying that each entry is actually a file before adding it to the list. It also filters out the current and parent directory entries, which scandir() always returns but which are rarely useful in UI contexts.
If you are working within the Laravel ecosystem, the approach shifts slightly due to the framework's reliance on absolute paths for security reasons. Laravel provides the Storage facade, which abstracts away the underlying driver (file, s3, etc.) and handles path resolution automatically. This is preferable because it prevents accidental exposure of local filesystem structures if a developer mistakenly uses relative paths that resolve incorrectly in different environments.
use Illuminate\Support\Facades\Storage;
$files = Storage::disk('public')->allFiles();
// Returns an array of file paths relative to the disk root
Using Storage ensures that you are interacting with files as intended by your application architecture, rather than guessing at filesystem quirks. Furthermore, if you need to handle a list of files for bulk operations like deletion or moving, Storage::disk()->files() provides a clean interface that returns only files, excluding directories entirely.
A common pitfall when reading directories is neglecting file permissions. Even if the path exists, if the web server user lacks execute permission on the directory or read permission on the files, PHP will throw an error or return an empty list depending on the function used. Always ensure your web.config or server configuration aligns with the code's expectations. Additionally, consider the overhead of calling realpath() inside a loop for very large directories; in high-traffic scenarios, caching the directory listing or using opendir()/readdir() might offer better performance, though the latter is less common in modern PHP development.
For advanced use cases involving specific file patterns or excluding certain extensions, you can combine these functions with regular expressions or simple string filtering to tailor the output exactly to your application's needs.
