Sort and display directory list alphabetically using opendir() in php

Sort and display directory list alphabetically using opendir() in php

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

Stefan Bogdanescu

Founder & Senior Architect

Sorting Directory Listings in PHP Without scandir()

When working with directory listings in PHP, the default behavior of opendir() combined with readdir() returns filenames in an arbitrary order that depends on the underlying filesystem implementation. On many Unix-like systems, this often corresponds to inode creation time rather than alphabetical order. If you are iterating through a folder to display images or generate thumbnails, relying on this natural order will result in unpredictable output unless you explicitly sort the results.

The core issue in the provided script is that asort() was attempted inside the while loop. This is a common mistake because asort() expects an array as its first argument, but $file at that point in the code is simply a string containing a single filename. Sorting a scalar string has no effect. To sort directory entries alphabetically, you must collect all filenames into an array first, apply the sorting function to that collection, and then iterate over the sorted data.

Here is the corrected approach using opendir() and readdir():

$handle = opendir('Images');
if ($handle !== false) {
    $files = [];
    
    // Collect all entries into an array
    while (false !== ($file = readdir($handle))) {
        // Skip the current directory entry, parent directory entry, 
        // and any specific files like index.php or a Thumbnails folder.
        if ($file !== '.' && $file !== '..' && $file !== 'index.php') {
            // Optional: Add additional logic here to check if the item is a file
            // rather than a directory using is_file() before adding to the list.
            $files[] = $file; 
        }
    }
    
    closedir($handle);

    // Sort the collected filenames alphabetically
    sort($files, SORT_STRING | SORT_LOCALE_LOCAL);

    echo '<ul>';
    foreach ($files as $file) {
        // Stripping extensions and symbols happens here or during output generation
        $displayName = str_replace(['.jpg', '.jpeg', '.png', '.gif', '.bmp', '_', '-'], '', $file);
        
        if (!empty($displayName)) {
            echo '<li><a href="Images/' . htmlspecialchars($file) . '" class="thickbox" rel="gallery" title="' . htmlspecialchars($displayName) . '"><img src="Images/Thumbnails/' . htmlspecialchars($file) . '" alt="' . htmlspecialchars($displayName) . '" width="300"></a></li>';
        }
    }
    echo '</ul>';
}

The critical line here is sort($files, SORT_STRING | SORT_LOCALE_LOCAL);. By default, sort() uses natural ordering in recent PHP versions, but explicitly passing SORT_STRING ensures alphabetical sorting based on character values. Using SORT_LOCALE_LOCAL makes the sort respect the current locale settings (e.g., ensuring that 'é' comes after 'e' in French locales), which is often desirable for user-facing content.

A significant trade-off with this approach is performance when dealing with large directories. Every time you call sort(), PHP performs an $O(N \log N)$ operation on the entire list of files. If your script runs once per request to display a gallery of thousands of images, sorting in memory might introduce noticeable latency compared to filesystem-level sorting.

For better performance in high-traffic applications, consider switching to scandir(). This function is a wrapper around opendir() and readdir() but returns the results as an array immediately. More importantly, you can pass the SCANDIR_SORT_ASC flag directly to scandir() to get a sorted list without needing to call sort() afterward:

// Returns a sorted array of files and directories in ascending order
$files = scandir('Images', SCANDIR_SORT_ASC | SCANDIR_SORT_NATURAL);

// Filter out . and .. and specific exclusions manually if needed, 
// or filter the returned array based on your logic.

This pattern eliminates the memory overhead of storing a large array in the loop and then sorting it later. It also simplifies the code by removing the need for a manual closedir() call in most scenarios, as scandir() handles the directory handle internally. However, if you strictly require the low-level control provided by opendir(), collecting and sorting manually remains the standard idiom.

Regardless of the method chosen, always remember to sanitize filenames before using them in HTML attributes like alt or title. The source material uses a simple str_replace for display names, but relying on client-side string manipulation to strip extensions is fragile. A more robust solution involves checking the file extension separately and constructing the display name programmatically, ensuring that special characters do not break your HTML structure.

Our network