Folder Recursion in PHP & Python


Read {count} times since 2020

A folder has files and sometimes sub directories. If we use the normal function for obtaining contents of a folder, we won’t get the details of the files in the sub directories. In this case, we have to look over into the sub folders and into other sub folders within this sub folder. This looking up of files deep down is called Recursive Folder Searching.

By doing this, we can search for a file or do various actions with each files thus recursed. An example case of this is the replacing softwares like regexxer. It uses recursion to replace a string to another in multiple files in the same directory even under any sub folders.

In this tutorial, you will see how to do this Recursion search of a folder in the **PHP **& Python programming languages. PHP have a builtin class for doing this, but complicated and for Python, it’s easier but have 2 loops.

PHP

It’s very short and effective. An array of files is made and it’s looped. Each file array will also have a SplFileInfo object to easily get the file info.

<?php
$path = realpath("/var/www/html");
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST); // Objects of different files
foreach($objects as $location => $object){
	$name = $object->getFileName(); // Get the file name
	echo "{$name} - {$location}n";
}
?>

The key of the returned array is the location and the value is the SplFileInfo object. Note that we use getFileName() function of the SplFileInfo object to retrieve the name of the file. We can use many others.

Python

import os
path = "/var/www/html"
for root, dirs, filenames in os.walk(path):
	for file in filenames:
		location = os.path.join(root, file)
		print file, "-", location

As you can see, we have two loops. One of the directories and the second of the files.

The first loop with os.walk(path) will fetch all the directories and the files in each of them. Then we loop over the files and prints the location and name of file.