List all files in one directory PHP

List all files in one directory PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Listing Directory Contents in PHP: Beyond opendir

There is no single $_SERVER variable that magically returns a list of files in a directory. The superglobal array is designed to hold request metadata, environment variables, and script paths, not filesystem enumeration results. To achieve the goal of listing files in a specific folder—such as usernames/—and generating hyperlinks for each, you need to interact directly with the operating system's directory entry mechanisms via PHP's standard library or modern alternatives like the Symfony Filesystem component.

The Standard Approach: opendir and scandir

The most common way to handle this in pure PHP is using the opendir() and readdir() functions, or their more convenient wrapper, scandir(). While opendir() works, it requires manual error handling and state management. You must remember to call closedir() when you are done, otherwise, file descriptors can leak in long-running scripts.

scandir() is generally preferred because it returns an array of filenames immediately. It also allows you to sort the output if needed. However, there is a critical detail regarding the contents of that array: scandir() includes . (current directory) and .. (parent directory). If your goal is to generate navigation links for only the actual files and folders within usernames/, you must explicitly filter these entries out.

Here is a robust implementation using scandir:

$directory = 'usernames';

if (!is_dir($directory)) {
    throw new RuntimeException("The directory '{$directory}' does not exist.");
}

// scandir returns all entries including '.' and '..'
$items = scandir($directory);

// Filter out the current and parent directory references
$filteredItems = array_diff($items, ['.', '..']);

echo '<ul>';
foreach ($filteredItems as $item) {
    // Construct the full path to ensure correct navigation
    $path = rtrim($directory, '/') . '/' . $item;
    
    echo '<li><a href="' . htmlspecialchars($path) . '">' . 
         htmlspecialchars(basename($path)) . '</a></li>';
}
echo '</ul>';

This approach works on almost every PHP configuration. The use of htmlspecialchars() is non-negotiable here. Since you are rendering filenames directly into HTML attributes and text content, an attacker could theoretically exploit a filename containing special characters to inject scripts or break out of the expected link structure if validation is skipped.

Modern Alternatives: Symfony Filesystem

If your application already utilizes the Symfony ecosystem or needs more advanced filesystem features (like checking file types, getting modification times, or walking subdirectories), the Symfony\Component\Finder component offers a cleaner abstraction. It abstracts away the underlying C functions and provides chainable methods.

use Symfony\Component\Finder\Finder;

$finder = new Finder();
$finder->in('usernames')
    ->files() // Only files, excluding directories if desired
    ->name('*.txt'); // Optional: filter by extension

foreach ($finder as $file) {
    echo '<a href="' . htmlspecialchars($file->getRealPath()) . '">' 
         . htmlspecialchars($file->getName()) . '</a><br>';
}

This method is particularly useful when you need to handle permission errors gracefully or when working within a specific path relative to the script's base directory. It abstracts the platform-specific differences in how directories are accessed, though under the hood it still relies on system calls like opendir or scandir.

Security and Permissions Pitfalls

When listing directory contents, you must respect server permissions. A common pitfall occurs when a script attempts to read a directory where the web server user (e.g., www-data) lacks read permissions. In such cases, PHP throws an exception that can be unhelpful if not caught properly. Always wrap your directory scanning logic in a try-catch block and check for specific exceptions like SplFileInfoException or generic errors.

Furthermore, ensure the target directory exists before attempting to scan it. Attempting to open a non-existent path will result in an error that might expose internal stack traces in development but should be handled gracefully in production.

Finally, consider what you are linking to. In many web applications, directories like usernames/ contain actual user data or sensitive information. Listing these files directly can aid directory traversal attacks if the links are not sanitized or if the application is served from a predictable document root. Always validate that the generated paths do not resolve outside the intended scope of the application before rendering them as clickable elements.

Our network