PHP: List all files in a directory.

In this beginner’s tutorial, I will show you how to list all files in a directory using PHP. We will do this using PHP’s glob function, which allows us to retrieve a list of file pathnames that match a certain pattern.

For this example, I have created a folder called “test”. Inside the folder, I have created three files:

  • test.txt
  • names.txt
  • file.php

Here is a screenshot of the directory:

Directory

In our first PHP code snippet, we will simply list everything that is in the test folder:

<?php

//Get a list of file paths using the glob function.
$fileList = glob('test/*');

//Loop through the array that glob returned.
foreach($fileList as $filename){
   //Simply print them out onto the screen.
   echo $filename, '<br>'; 
}

The result will look something like this:

test/file.php
test/names.txt
test/test.txt

However, what if we wanted to list all files with a particular file extension? i.e. What if we only want to list the .txt files and not the .php file that is currently present?

Well, the solution is pretty simple:

//Get a list of all files ending in .txt
$fileList = glob('test/*.txt');

In the code snippet above, we told the glob function to return a list of file pathnames that ended .txt

Warning: In some cases, the folder may have subdirectories. In cases where you are listing everything that is inside a specified folder, these subdirectories will be returned by the glob function. To avoid printing out or interacting with subdirectories, you can simply use the is_file function to confirm that the file pathname in question leads to an actual file:

<?php

$fileList = glob('test/*');
foreach($fileList as $filename){
    //Use the is_file function to make sure that it is not a directory.
    if(is_file($filename)){
        echo $filename, '<br>'; 
    }   
}

Hopefully, this tutorial was useful!

Related: Delete all files in a folder using PHP.