How to Search All Subfolders using PHP

Home » Coding » How to Search All Subfolders using PHP

How to Search All Subfolders using PHP

Here's how to search through a folder and all its subfolders using PHP.

Searching through a directory to process files is usually not difficult with PHP; you simply use the scandir function and specify which directory you want to search in. The result is returned in an array which you can then process as desired, for example by using a foreach loop.

However, a limitation of this method is that scandir() does not automatically search through subfolders - so how do you do that?

Search through subfolders

To search through the folder and all its subfolders, we use two PHP functions:

  1. RecursiveIteratorIterator, which loops through all elements in a structured tree
  2. RecursiveDirectoryIterator, which creates a structured tree of the specified path

When these two functions are combined, we get exactly what we want; a clear overview of all elements in the directory we want to search - everything in the folder and all its subfolders.

PHP code

To accomplish this in a PHP script, I've put together the following:

$path = '/your/folder/';
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
foreach ($files as $file) {
    if ($file->isDir()) { continue; }
    $list[] = $file->getPathname();
}

To explain what's happening in this script, here's a breakdown:

  1. Specify your path in the $path variable
  2. Search through the path using the functions we mentioned earlier, and store the results in the $files variable
  3. Loop through the results we obtained when searching through the path using the foreach() function
  4. We check if it's a directory using $file->isDir(), which returns true if it's a folder and false if it's not a folder
  5. If it's a folder, we move to the next one using continue()
  6. If instead, it's a file, we add the name and path of the file to an array stored in the variable $list

Now we have a complete list of all files in the folder we wanted to search in, as well as all its subfolders.

The script isn't too long and has a comfortable length, and although the article is quite long — since I want to explain why and how I did what I did — this is an easy and comfortable method for going through all files.


Details

  • Title: Tutorial: Search All Subfolders using PHP
  • Published:
  • Author:
  • Categories: PHP
Top Hosting Providers
Price

Want help?

Sometimes it can be hard to make a choice. Have you still not foun the information you're looking for, or are you wondering about something specific? Get in touch and we'll help you out.

Get in touch