PHP Listing Files in a Directory – A Complete Guide

Listing files in a directory is a common task in PHP, useful for file management, creating galleries, listing logs, or scanning directories for processing. PHP provides several methods to list files and directories using built-in functions like scandir(), opendir(), readdir(), and glob().

This tutorial covers:

1. Listing Files Using scandir()

The scandir() function returns an array of filenames in a directory.

Example: Basic Listing of Files

$dir = "example_folder";
$files = scandir($dir);

print_r($files);

Output Example

Array
(
    [0] => .
    [1] => ..
    [2] => file1.txt
    [3] => image.jpg
    [4] => subfolder
)

Explanation

  • “.” and “..” represent the current and parent directories.
  • The function returns all files and directories in the specified path.

2. Filtering Files and Ignoring . and ..

Since scandir() includes . and .., we can filter them out.

Example: Ignore . and ..

$dir = "example_folder";
$files = array_diff(scandir($dir), array('.', '..'));

print_r($files);

Output

Array
(
    [2] => file1.txt
    [3] => image.jpg
    [4] => subfolder
)

Use Case: Cleaning up directory listings.

3. Checking If It’s a File or a Directory

To differentiate between files and directories, use is_dir().

Example: Separate Files and Directories

$dir = "example_folder";
$files = array_diff(scandir($dir), array('.', '..'));

foreach ($files as $file) {
    if (is_dir("$dir/$file")) {
        echo "[DIR] $file\n";
    } else {
        echo "[FILE] $file\n";
    }
}

Output

[FILE] file1.txt
[FILE] image.jpg
[DIR] subfolder

Use Case: Generating a structured file manager.

4. Listing Files Using opendir() and readdir()

The opendir() function opens a directory, and readdir() reads filenames one by one.

Example: List Files One by One

$dir = "example_folder";

if ($handle = opendir($dir)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            echo "$file\n";
        }
    }
    closedir($handle);
}

Explanation

  • opendir() opens a directory.
  • readdir() reads each entry one at a time.
  • closedir() closes the directory after processing.

Use Case: Memory-efficient when handling large directories.

5. Using glob() for Pattern Matching

The glob() function allows filtering files by extensions or patterns.

Example: Get Only .txt Files

$txtFiles = glob("example_folder/*.txt");

print_r($txtFiles);

Output

Array
(
    [0] => example_folder/file1.txt
    [1] => example_folder/log.txt
)

Use Case: Selecting specific file types like *.jpg, *.pdf, etc.

6. Listing Files Recursively (Subdirectories)

To list all files, including subdirectories, we need recursion.

Example: Recursively List Files in a Directory

function listFilesRecursive($dir) {
    $files = scandir($dir);
    
    foreach ($files as $file) {
        if ($file == "." || $file == "..") continue;

        $filePath = "$dir/$file";

        if (is_dir($filePath)) {
            echo "[DIR] $filePath\n";
            listFilesRecursive($filePath); // Recursive call
        } else {
            echo "[FILE] $filePath\n";
        }
    }
}

listFilesRecursive("example_folder");

Output

[DIR] example_folder/subfolder
[FILE] example_folder/subfolder/note.txt
[FILE] example_folder/file1.txt
[FILE] example_folder/image.jpg

Explanation

  • Uses recursion to scan nested folders.
  • Detects directories and calls itself recursively.

Use Case: Searching for files, backup scripts, or generating file trees.

7. Combining Filters and Sorting

We can sort files by name, size, or date.

Example: Sorting Files by Last Modified Date

$dir = "example_folder";
$files = array_diff(scandir($dir), array('.', '..'));

usort($files, function($a, $b) use ($dir) {
    return filemtime("$dir/$a") - filemtime("$dir/$b");
});

print_r($files);

Explanation

  • filemtime($file) gets the last modified timestamp.
  • usort() sorts files by modification time.

Use Case: Sorting log files or media files by date.

8. Creating an HTML File List

To display files in a web page, we can generate an HTML file list.

Example: Display Files as Clickable Links

$dir = "example_folder";
$files = array_diff(scandir($dir), array('.', '..'));

echo "<ul>";
foreach ($files as $file) {
    echo "<li><a href='$dir/$file'>$file</a></li>";
}
echo "</ul>";

Output (Rendered in Browser)

  • file1.txt
  • image.jpg
  • subfolder

Use Case: Building a simple file browser.


Comparison of File Listing Methods

Method Best For Features
scandir() Simple file listing Returns an array of files & directories
opendir() + readdir() Large directories Efficient, reads one file at a time
glob() Pattern-based search Filters files by extensions or names
Recursive function Nested directories Scans subdirectories recursively

Conclusion

  • PHP provides multiple ways to list files and directories.
  • scandir() is simple and efficient for small folders.
  • opendir() + readdir() is memory-efficient for large directories.
  • glob() allows file filtering based on extensions.
  • Recursion is needed to scan subdirectories.
  • Sorting files by date, name, or size is possible using usort().
  • For web applications, generate HTML links dynamically.

By understanding these methods, you can list, filter, and manipulate files efficiently in PHP for file management, automation scripts, or web-based file browsers.

Related posts

PHP Static Methods: A Tutorial with Examples

PHP Deleting Files: A Tutorial with Examples

PHP Copying Files: A Tutorial with Examples