19.9. Processing All Files in a Directory
Problem
You want to do something to all the files in a directory and in any subdirectories.
Solution
Use the pc_process_dir( )
function, shown in Example 19-1, which returns a list of all files in and
beneath a given directory.
Example 19-1. pc_process_dir( )
function pc_process_dir($dir_name,$max_depth = 10,$depth = 0) { if ($depth >= $max_depth) { error_log("Reached max depth $max_depth in $dir_name."); return false; } $subdirectories = array(); $files = array(); if (is_dir($dir_name) && is_readable($dir_name)) { $d = dir($dir_name); while (false !== ($f = $d->read())) { // skip . and .. if (('.' == $f) || ('..' == $f)) { continue; } if (is_dir("$dir_name/$f")) { array_push($subdirectories,"$dir_name/$f"); } else { array_push($files,"$dir_name/$f"); } } $d->close(); foreach ($subdirectories as $subdirectory) { $files = array_merge($files,pc_process_dir($subdirectory,$max_depth,$depth+1)); } } return $files; }
Discussion
Here’s an example: if /tmp
contains the files a and b,
as well as the directory c, and
/tmp/c contains files d and
e,
pc_process_dir('/tmp')
returns an array with elements
/tmp/a, /tmp/b,
/tmp/c/d, and /tmp/c/e. To
perform an operation on each file, iterate through the array:
$files = pc_process_dir('/tmp'); foreach ($files as $file) { print "$file was last accessed at ".strftime('%c',fileatime($file))."\n"; }
Instead of returning an array of files, you can also write a function that processes them as it finds them. The ...
Get PHP Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.