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:
RecursiveIteratorIterator
, which loops through all elements in a structured treeRecursiveDirectoryIterator
, 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:
- Specify your path in the
$path
variable - Search through the path using the functions we mentioned earlier, and store the results in the
$files
variable - Loop through the results we obtained when searching through the path using the
foreach()
function - We check if it's a directory using
$file->isDir()
, which returnstrue
if it's a folder andfalse
if it's not a folder - If it's a folder, we move to the next one using
continue()
- 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: Andrew Young
- Categories: PHP