List Files In Directory With PHP

Listing a set of files in a specified directory is a joyous task with PHP. There is a particular function, specifically created for this use-case, and it doesn’t take much to use it either. In this article, a range of ways to get a directories contents will be explored.

The particular function that will be used throughout this article is the scandir() function.

Examples

Avoiding a common problem

Throughout the examples to follow, you will notice an extra function being used, namely, array_diff(). The reason being is that by default, scandir() will include the reference to the current and parent directory in its output. These will be in the form of a period and a double period.

If you only want to list files, and not have to handle these extra values within the scanned directory array, you can remove them as you search with array_diff().

Here is an partial example of a scandir() output

Array ( [0] => . [1] => .. [2] => 
....

As you can imagine, these values can be problematic and therefore, in each example, will be removed. Alternatively, this function can be removed from the examples with the main functionality in tact. But of course, you will have these additional values in play.

List all files in the current directory

Grabbing the contents of the current directory is pretty straight forward. With the ability to use the __dir__ magic constant, you can easily access the string-form-value path of the current directory. This is exactly what will be passed into the scandir() method. Here is an example.

PHP

$rootDir = __DIR__; // __DIR__ = C:\xampp\htdocs\CodeWall

$allFiles = array_diff(scandir($rootDir . "/"), [".", ".."]); // Use array_diff to remove both period values eg: ("." , "..")

print_r($allFiles);

Output

Array ( [2] => css [3] => img [4] => index.php [5] => js [6] => page1.php [7] => page2.php )

List all files alphabetically ordered

So, let’s say we wanted to list files in order of how they are named, we can do that by adding a second parameter to the scandir() function. As a side-note, this function already lists files alphabetically in an ascending order, it’s only if you want descended sort, there is a must to add the second parameter. The parameter is a simple integer and the value is 1 for descending. Let’s see it in action.

PHP

$rootDir = __DIR__; // __DIR__ = C:\xampp\htdocs\CodeWall

$allFiles = array_diff(scandir($rootDir . "/", 1), [".", ".."]); // Use array_diff to remove both period values eg: ("." , "..")

print_r($allFiles);

Output

Array ( [0] => page2.php [1] => page1.php [2] => js [3] => index.php [4] => img [5] => css )

List all files in current and sub-directories

In this last example, getting an array of each and every folder and file that exist in your whole project directory will be explored. Here is a quick explanation of what is done in the code –

  1. Get the whole current directory items
  2. Loop through the items, checking if the path of the root directory added with any of the items is another directory.
  3. If so, then scan that directory and add it to the files array too.

The output may not be very elegant, but with a little manipulation, it could be made into a nice, tree-style view.

PHP

$rootDir = __DIR__; // __DIR__ = C:\xampp\htdocs\CodeWall

$currentDirectoryItems = array_diff(scandir($rootDir . "/", 1), [".", ".."]); // Use array_diff to remove both period values eg: ("." , "..")
$allFiles = [];
foreach ($currentDirectoryItems as $value) {
    $allFiles[] = $value;

    if (is_dir($rootDir . "/" . $value)) { // Check if specified path is a directory
        $allFiles[] = array_diff(scandir($rootDir . "/" . $value), [".", ".."]); // Use array_diff to remove both period values eg: ("." , "..");
    }
}
print_r($allFiles);

Output

Array ( [0] => page2.php [1] => page1.php [2] => js [3] => Array ( [2] => bootstrap.js [3] => jquery-1.10.2.js ) [4] => index.php [5] => img [6] => Array ( [2] => img1.jpg [3] => img2.jpg ) [7] => css [8] => Array ( [2] => Site.css [3] => bootstrap.css ) )

As you can see from the output above, it could look better, but its succeeded in the job at hand. The image folder and it’s contents has been added along with the CSS and JS folders too.

Summary

The scandir() function is another proven example of how PHP does a-lot of ground work for us. All we need to worry about is specifying a simple path and PHP does the rest. If you want to go into depth with this function, check out the documentation here.

List Files In Directory With PHP
Posted in PHP

You May Also Like

Leave a Reply

Your email address will not be published.