Skip to content

Instantly share code, notes, and snippets.

@JamesPhillipsUK
Last active December 28, 2019 17:07
Show Gist options
  • Select an option

  • Save JamesPhillipsUK/cb9f9391998896b5101ac9d6a99fbecb to your computer and use it in GitHub Desktop.

Select an option

Save JamesPhillipsUK/cb9f9391998896b5101ac9d6a99fbecb to your computer and use it in GitHub Desktop.
Depth-First Filesystem Traversal in PHP

Depth-First Filesystem Traversal in PHP

Whilst working on BlogDraw-Updater earlier this week, I created a nifty little system for filesystem traversal in PHP which I thought I'd share with you all because it might be useful. At the very least, it could save a couple of people some time writing something like this out themselves.

It uses depth-first traversal to locate every file in a filesystem, implemented through a recursive function (traverse). "traverse" takes a filepath (either relative, or absolute) to a directory and locates all files and directories within it. It also locates all files and directories in those directories, and so on until it's mapped out the entire filesystem.

Conventions

I've chosen to demonstrate a couple of unusual conventions here, namely:

  • I've broken printed lines with the newline character \n, for compatibility with PHP CLI, if you were to implement this through a web interface, you'd either want to call the nl2br() function on these, or replace them with <br /> tags.
  • Using scandir() and printing directories before the if statement which prevents infinite recursion allows us to print the "." and ".." directory entries, because they're present in the directory even though we've no need to traverse them.
<?php
traverse("relative/filepath/string");
function traverse($dir)
{
echo "Traversing: " . realpath($dir) . "\n";
$files = scandir(realpath($dir));
foreach ($files as $file)
{
if (is_dir(realpath($dir) . '/' . $file))// If it's a directory, we want to traverse through that too.
{
echo "Located Directory: " . realpath($dir) . '/' . $file . "\n";
if ($file != '.' && $file != '..')// Scandir gives pointers to . and .. causing infinite recursion.
traverse(realpath($dir) . '/' . $file);// Increase traversal depth.
}
else
echo "Located File: " . realpath($dir) . '/' . $file . "\n";
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment