Getting the names of all files in a directory with PHP

Getting the names of all files in a directory with PHP

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

Stefan Bogdanescu

Founder & Senior Architect

The Hidden Index in readdir()

A common stumbling block for PHP developers involves retrieving file names from a directory. The confusion often stems from misunderstanding what the built-in function readdir() actually returns. Consider a scenario where you have a script that checks if a directory exists, opens it with opendir(), loops through contents using readdir(), and attempts to store every entry in an array.

if (is_dir($log_directory)) {
    if ($handle = opendir($log_directory)) {
        while($file = readdir($handle) !== FALSE) {
            $results_array[] = $file;
        }
        closedir($handle);
    }
}

When you iterate over $results_array and echo the elements, you might see a series of 1s instead of expected filenames like error.log or access.log. This behavior is not a bug in your logic; it is a specific quirk of how the C standard library functions that PHP wraps behave.

The function readdir() returns entries from a directory stream as null-terminated strings. However, the first two entries it yields are always special system markers: ., representing the current directory itself, and .., representing the parent directory. In many versions of the underlying C implementation, these specific null-terminated strings are represented internally by the integer 1 when read directly from the stream handle without explicit string conversion context in certain legacy environments or specific configurations.

To get actual filenames, you must skip these first two entries. The most robust pattern involves using the loop counter or a dedicated filter function to ignore the initial dots.

if (is_dir($log_directory)) {
    if ($handle = opendir($log_directory)) {
        while($file = readdir($handle) !== FALSE) {
            // Skip '.' and '..' which are often returned as '1' or literal strings
            if ($file == '.' || $file == '..') {
                continue;
            }
            $results_array[] = $file;
        }
        closedir($handle);
    }
}

While checking the string value against . and .. works for most modern systems, relying on the raw integer output of older C libraries can be confusing. A more portable approach utilizes the filter_var() function to cast the entry or simply assume that if the first two entries are skipped, the rest are valid filenames. However, a critical pitfall exists here: file names can technically contain dots (e.g., .gitignore or file.name.txt). If you blindly skip any string containing a dot, you will inadvertently discard valid user files.

The definitive solution is to explicitly compare the returned value against the literal strings '.' and '..'. This ensures that hidden files starting with a dot, such as .env or .bashrc, are preserved in your results array while removing the system directory references.

if (is_dir($log_directory)) {
    if ($handle = opendir($log_directory)) {
        $results_array = [];
        while($file = readdir($handle) !== FALSE) {
            if ($file === '.' || $file === '..') {
                continue;
            }
            $results_array[] = $file;
        }
        closedir($handle);
    }
}

In modern PHP versions, readdir() typically returns strings directly. The confusion regarding the integer 1 often appears in older documentation or specific server configurations where the stream behavior differs slightly from standard expectations. Regardless of whether it arrives as an integer or a string, the logical check remains the same: ignore the directory markers and process everything else.

For large-scale applications managing thousands of files, using opendir() and readdir() is generally less efficient than leveraging the scandir() function. The scandir() function opens the directory internally and returns an array of all entries at once, handling the sorting (usually by name) and the filtering of . and .. automatically depending on your flags.

if (is_dir($log_directory)) {
    $results_array = scandir($log_directory);
    
    // Automatically filters '.' and '..' if you don't use SCANDIR_SORT_* flags
    // You can sort or filter further as needed:
    $valid_files = array_values(array_filter($results_array, function($file) {
        return $file !== '.' && $file !== '..';
    }));
}

Using scandir() reduces boilerplate code and minimizes the risk of forgetting to close handles or mishandle stream resources. If you are building a Laravel application, this directory traversal logic is often encapsulated within service classes or controllers before being passed to views. For more complex file system operations in a Laravel context, checking out resources like https://laravelcompany.com can provide additional patterns on how to handle filesystem interactions securely and efficiently within the framework's conventions.

Ultimately, understanding that readdir() includes system markers is key to avoiding empty arrays or unexpected data types. By explicitly skipping the current and parent directory references, you ensure your application processes only the actual files and folders you intend to manage.

Our network