How to List Files and Folders in a Directory Using PHP
Listing the contents of a directory is a fundamental operation in server-side development, often required for generating file trees, displaying user avatars, or managing dynamic content. While the conceptual goal is straightforwardâretrieve a list of items within system/information/âthe implementation details dictate how robust your solution will be. The most common approach involves using the built-in PHP function scandir().
This function returns an array of filenames from a directory, including hidden files and directories. It accepts an optional parameter for the order of the results. For example, you can retrieve entries sorted by name or by modification time if needed. However, simply calling scandir() provides only the base names without context regarding whether an item is a file or a folder. To replicate the output structure shown in your example, where specific folders like "User" contain distinct text files, you must iterate through the returned array and inspect each entry's type.
To achieve this, combine scandir() with the is_dir() function. This check allows you to categorize entries into two distinct groups: directories and files. You can then output them accordingly. Here is a basic implementation pattern:
$dirPath = 'system/information';
$entries = scandir($dirPath);
foreach ($entries as $entry) {
// Skip the current ('.') and parent ('..') directory entries
if ($entry === '.' || $entry === '..') {
continue;
}
$fullPath = rtrim($dirPath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $entry;
if (is_dir($fullPath)) {
echo "<strong>Folder</strong> - " . htmlspecialchars($entry) . "<br>";
// Optional: List files within the subdirectory
$subFiles = scandir($fullPath);
foreach ($subFiles as $file) {
if ($file !== '.' && $file !== '..') {
echo "<strong>Files From " . basename($entry) . "</strong> - " . htmlspecialchars($file) . "<br>";
}
}
} else {
// Handle top-level files if they exist outside the subfolders
echo "<strong>File</strong> - " . htmlspecialchars($entry) . "<br>";
}
}
In this example, we explicitly skip the . and .. entries returned by scandir(), which represent the current directory and its parent. Failing to filter these out can lead to unexpected behavior in loops or incorrect path constructions. The code also utilizes rtrim() on the $dirPath to ensure that when we append a filename, we do not end up with double slashes (//) or malformed paths, depending on the operating system's directory separator.
A critical consideration when implementing this logic is security. If you are displaying file lists to users, always sanitize output using htmlspecialchars(). This prevents Cross-Site Scripting (XSS) vulnerabilities if filenames contain malicious characters or scripts. Additionally, be aware of permission issues. The PHP process must have read and execute permissions on the target directory; otherwise, scandir() will fail silently or throw a warning depending on your error reporting settings.
For projects built on the Laravel framework, you might find yourself needing to access file system operations within controllers or services. While Laravel provides an underlying filesystem facade for more complex tasks like mounting virtual directories or managing cloud storage, standard PHP functions like scandir() remain perfectly valid and performant for simple directory listing tasks. If you require a more opinionated approach or need to integrate this logic into an existing application architecture, resources such as LaravelCompany offer guidance on leveraging the framework's ecosystem while maintaining compatibility with native PHP capabilities.