How to list files in a directory in PHP

“Above all else, show the data.” — Edward R. Tufte

Key takeaways:

  • Listing files in a directory is essential for web applications and file management.

  • Methods: scandir(), glob(), and readdir().

    • scandir(): This is a simple method that returns all entries (files and directories).

    • glob(): This is a pattern-based filtering method that may have performance limitations.

    • readdir(): This method is manually handled and requires additional filtering.

  • A method should be chosen based on simplicity, filtering, performance, or PHP extension requirements.

Displaying the list of files in a directory is a common task in web development. Imagine we’re creating a web application that allows users to download files from a specific directory. For this purpose, we need to list files to provide users with a view of available files for download. PHP provides several methods to accomplish this.

Methods to list files of a directory

We’ll go through three methods to list files in a directory:

  • Using scandir()

  • Using glob()

  • Using readdir()

Method 1: Using scandir() to list files of a directory

The scandir() function in PHP is used to scan a directory and retrieve a list of its contents, including both files and directories. It takes the directory path as a parameter and returns an array of strings containing the names of the files and directories in that directory. The entries include both the current directory (.) and the parent directory (..). Let’s examine the example code:

<?php
$arrFiles = array();
$dirPath = "./MyFolder";


// Using scandir()
echo "--------------------------------<br>";
echo "Method 1: Using scandir() <br>";
echo "--------------------------------<br>";
$files = scandir($dirPath);
foreach ($files as $file) {
    $filePath = $dirPath . '/' . $file;
    if (is_file($filePath)) {
        echo $file . "<br>";
    }
}
?>
Code to list files in PHP using scandir()

We use scandir($dirPath) to retrieve an array of files and directories. We then use a foreach loop to iterate over each entry in the resulting array. For each entry, we construct the file path by concatenating the directory path, a forward slash, and the current entry. By using the is_file() function, we determine if the constructed file path represents a file. If it does, we display the file name. This is done to filter out the directories.

Pros:

  • Simple and commonly used method

Cons:

  • Retrieves all entries, including directories (requires additional filtering if only files are needed)

Method 2: Using glob() to list files of a directory

The glob() function is a versatile file system function that is used to retrieve a list of file names or paths based on a specified pattern or wildcard. It takes a string parameter that represents the pattern to match against the file names. The function searches for files that match the pattern within the specified directory and returns an array of the matching file names or paths.

<?php
$arrFiles = array();
$dirPath = "./MyFolder";
    
// Method 2: Using glob()
echo "--------------------------------<br>";
echo "Method 2: Using glob() <br>";
echo "--------------------------------<br>";
$files = glob($dirPath . "/*");
foreach ($files as $file) {
    if (is_file($file)) {
        echo basename($file) . "<br>";
    }
}

echo "--------------------------------<br>";
echo "Display files ending in .txt<br>";
echo "--------------------------------<br>";
$files = glob($dirPath . "/*.txt");
foreach ($files as $file) {
    if (is_file($file)) {
        echo basename($file) . "<br>";
    }
}

?>
Code to list files in PHP using glob()

In this code, we invoke glob($dirPath . "/*") to obtain an array of file names within the directory specified by the variable $dirPath. The pattern "/*" is appended to the directory path to match all files within that directory. The resulting array of file names is stored in the variable $files. Next, we utilize a foreach loop to iterate over each file name in the $files array. Within the loop, we check if the current file name represents a file using the is_file() function. If it does represent a file, we extract the base name of the file using basename($file), which removes the directory path portion. On line 19, we invoke glob($dirPath . “/*.txt”) that obtains an array of only those file names that end in .txt. This is useful in scenarios where we need to filter out a particular type of file.

Pros:

  • Simpler and concise code

  • Easy filtering of files and directories using patterns

Cons:

  • May have performance issues with a large number of files

Method 3: Using readdir() to list files of a directory

The readdir() function in PHP is used to read the contents of a directory one entry at a time. It takes a directory handle as a parameter, which is obtained by opening the directory using the opendir() function. After processing, it is important to close the directory handle using the closedir() function. closedir() ensures that system resources associated with the directory handle are properly released.

<?php
$arrFiles = array();
$dirPath = "./MyFolder";

// Method 3: Using opendir(), readdir(), and closedir()
if ($handle = opendir($dirPath)) {
    echo "--------------------------------<br>";
    echo "Method 3: Using readdir()<br>";
    echo "--------------------------------<br>";
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != ".." && is_file($dirPath . '/' . $entry)) {
        echo $entry . "<br>";
        }
    }
    closedir($handle);

} else {
    echo "Failed to open directory.";
}

?>
Code to list files in PHP using readdir()

In this method, we first open the directory using opendir($dirPath), where $dirPath represents the path to the target directory. If the directory opening is successful, we iterate over the directory entries using readdir($handle) until false is returned, which indicates the end of the directory. We exclude the current directory ("."), parent directory (".."), and folders (is_file($dirPath . '/' . $entry)). Finally, we close the directory handle using closedir($handle).

Pros:

  • No additional PHP extensions are required

Cons:

  • Requires manual handling of directory entries

  • Requires additional filtering if only files are needed

Summary

Here’s a comparison table highlighting the key features of these three methods.

Comparison of readdir(), glob(), and scandir()

Feature

readdir()

glob()

scandir()

Main Functionality

 Returns the next entry in a directory

List files and directories that match specified pattern

Lists files and directories

Code Simplicity

Requires more code

Concise code

Simple code

Performance

Suitable for small directories

Can be slow with large directories

Suitable for most scenarios

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How do we find specific files in a directory in PHP?

We can find specific files in a directory in PHP using the glob() method.


How do we find the number of files in a directory PHP?

To find the number of files in a directory PHP, use the count() function combined with scandir() or glob().

$files = scandir($dirPath);

// Filter out unwanted entries
$files = array_diff($files, array('.', '..'));

// Count the number of files
$fileCount = count($files);

How can we know the current working directory?

The getcwd() function is used to know the current working directory.


How does PHP list files in a directory along with their date and size?

We can use scandir() combined with filemtime() and filesize() to list files with modification date and size.


How do we list files in a directory sorted by name in PHP?

We can use the scandir() function and then sort the resulting array using PHP natsort().


Free Resources

Copyright ©2024 Educative, Inc. All rights reserved