How to list files in a directory in PHP

Listing files in a directory is a common task in web development, and PHP provides several methods to accomplish this.

We will go through three methods to list files of a directory:

  • Using scandir()

  • Using glob()

  • Using readdir()

Using scandir()

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).

Using glob()

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>";
    }
}

?>
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.

Pros:

  • Simpler and concise code.

  • Easy filtering of files and directories using patterns.

Cons:

  • Requires the glob() function, which is not available in all PHP configurations.

  • May have performance issues with a large number of files.

Using readdir()

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() 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.

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

Additional Requirement

No

globe()

No

Code Simplicity

Requires more code

Concise code

Simple code

Performance

Suitable for small directories

Can be slow with large directories

Suitable for most scenarios

Copyright ©2024 Educative, Inc. All rights reserved