How to List Files & Folders Of a Directory Using PHP

Listing files in a directory using PHP is a common operation in web development. Whether you’re building a file management system, creating a gallery, or processing uploaded files, PHP provides powerful functions to interact with the file system. In this tutorial you will learn how to list files in a directory using PHP, covering various methods and best practices.

Sample Folder Structure:

Here is a dummy uploads folder structure that we will use for demonstration:

uploads/
├── images/
│   ├── profile.png
│   └── cover.png
├── index.html
└── script.js

Set the Directory Path:

Before you can list files in a directory, you need to access that directory using PHP. You can specify the directory’s path using an absolute or relative path. To access a directory named “uploads” located in the same directory as your PHP script, you can use a relative path:

$directory = 'uploads/';

For an absolute path, specify the full path to the directory:

$directory = '/var/www/html/uploads/';

Use scandir() Function to Scan the Directory:

PHP’s scandir() function is a simple way to list files and directories in a given directory. It returns an array containing the names of all files and directories found in the specified directory.

$files = scandir($directory);
  • $directory: The path to the directory you want to list files in.
  • $files: An array containing the names of files and directories.
<?php
$directory = 'uploads/';
$files = scandir($directory);

foreach ($files as $file) {
    echo $file . "\n";
}
.
..        
images    
index.html
script.js

Filter Out the “.” and “..” Entries:

When using scandir(), keep in mind that it includes the special entries “.” (current directory) and “..” (parent directory) in the result. You’ll often want to filter out these entries, as they are not actual files.

<?php
// Define the directory where files are stored
$directory = 'uploads/';

// Get the list of files in the directory
$files = scandir($directory);

// Loop through each file in the directory
foreach ($files as $file) {
    // Exclude current directory (.) and parent directory (..)
    if ($file != '.' && $file != '..') {
        // Output the file name
        echo $file . "\n";
    }
}
images    
index.html
script.js

List Files Only using PHP:

If you want to list only files (not directories), you can filter the results using is_file(). The following PHP code will list only files in the “uploads” directory.

<?php
$directory = 'uploads/';
$files = scandir($directory);

foreach ($files as $file) {
    $filePath = $directory . $file;

    // Check if the item is a file (not a directory)
    if (is_file($filePath)) {
        // Output the file name
        echo $file . "\n";
    }
}
index.html
script.js

Directory and its Subdirectories Listing in PHP:

To list files in a directory and its subdirectories recursively, you can create a recursive function or use libraries like RecursiveDirectoryIterator and RecursiveIteratorIterator. The PHP code given in the below will list files in the “uploads” directory and all its subdirectories.

<?php
function listFilesRecursive($directory) {
    // Create a new RecursiveDirectoryIterator to iterate through the directory recursively
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));

    // Loop through each item in the iterator
    foreach ($iterator as $file) {
        // Check if the item is a file
        if ($file->isFile()) {
            // Output the file path
            echo $file->getPathname() . "\n";
        }
    }
}

// Define the directory to search for files recursively
$directory = 'uploads/';

// Call the function to list files recursively in the specified directory
listFilesRecursive($directory);
uploads\images\cover.png  
uploads\images\profile.png
uploads\index.html        
uploads\script.js

Listing files in a directory using PHP is a crucial skill for various web development tasks. Whether you need to display a list of downloadable files, organize uploaded content, or perform file-related operations, PHP’s file system functions provide the tools you need. By following this guide, you’ll be able to navigate directories, filter files and directories, and even perform recursive directory listing, all with ease and confidence.

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies to ensure that we give you the best experience on our website. Privacy Policy