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.
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 thenl2br()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.