Skip to main content

Practical-12

Write a PHP Program to Recursive Traversals of Directory.

Introdution

A recursive traversal of a directory refers to the process of traversing each element (file or directory) within a directory. It is named recursive because it performs the same action over and over again, i.e. traversing a directory, until each element has been traversed. This is done by starting from a root directory, and then traversing its elements one at a time, until all the elements with it has been traversed. When understood correctly, this process can be immensely useful for certain programming tasks such as listing all the files within a directory and its subdirectories.

Having knowledge about how recursive data structures are used is important for developing a strong foundation for programming. Being familiar with the concepts of recursion, looping, pattern matching, and data structures will enable you to create powerful programs. After this introduction, one will able to understand the importance of recursive data structures, learn basic programming language syntax to traverse directories, and be familiar with best practices when using recursive data structures in programming.

Code

<?php
// Declare a recursive function
function recursiveDirectoryTraversal($root) {
// Initialize a static variable to keep track of the depth of the directory
static $depth = 0;

// List all of the files in the specified directory
$fileList = scandir($root);

// Loop through each of the files in the directory
foreach ($fileList as $entry) {
// Increment the directory depth
$depth++;

// Ignore the current and parent directories
if ($entry != '.' && $entry != '..') {
$fullPath = $root . "/" . $entry;

// Output the file name
echo str_repeat(' ', $depth) . $entry . "\n";

// If the entry is a directory, recall the function
if (is_dir($fullPath)) {
recursiveDirectoryTraversal($fullPath);
}
}

// Decrement the directory depth
$depth--;
}
}

// Call the recursiveDirectoryTraversal()
recursiveDirectoryTraversal('/path/to/directory');

Output

 folder_name
file_name_1
file_name_2
inner_directory
inner_file_name_1
inner_file_name_2
Explanation

This code loops through the files of the directory and its subdirectories by using recursion. It takes in a root directory as an argument and uses a static variable called $depth to track the directory depth. The function then scans the directory and adds each file name into the $fileList variable. Foreach loop is used to iterate through the files. The code ignores the current and parent directories and the full path of the file is specified. Next, the file name is outputted with the str_repeat() method. The is_dir() method is used to check if the path is a directory or file. If it is a directory, then the function will recall itself with the specified directory.

Get Help