A very flexible function to recursively list all files in a directory with the option to perform a custom set of actions on those files and/or include extra information about them in the returned data.
----------
SYNTAX:
$array = process_dir ( $dir , $recursive = FALSE )
$dir (STRING) = Directory to process
$recursive (BOOLEAN) = [Optional] Recursive if set to TRUE
RETURN VALUES:
The function returns an indexed array, one entry for every file. Each entry is an associative array, containing the basic information 'filename' (name of file) and 'dirpath' (directory component of path to file), and any additional keys you configure. Returns FALSE on failure.
----------
To allow you to configure another key, the entry for each file is stored in an array, "$entry" for each iteration. You can easily return any additional data for a given file using $entry['keyname'] = ... (Note that this data can be any variable type - string, bool, float, resource etc)
There is a string variable "$path" available, which contains the full path of the current file, relative to the initial "$dir" supplied at function call. This data is also available in it's constituent parts, "$dir" and "$file". Actions for each file can be constructed on the basis of these variables. The variables "$list", "$handle" and "$recursive" should not be used within your code.
----------
Simply insert you code into the sections indicated by the comments below and your away!
The following example returns filename, filepath, and file modified time (in a human-readable string) for all items, filesize for all files but not directories, and a resource stream for all files with 'log' in the filename (but not *.log files).
<?php
function process_dir($dir,$recursive = FALSE) {
if (is_dir($dir)) {
for ($list = array(),$handle = opendir($dir); (FALSE !== ($file = readdir($handle)));) {
if (($file != '.' && $file != '..') && (file_exists($path = $dir.'/'.$file))) {
if (is_dir($path) && ($recursive)) {
$list = array_merge($list, process_dir($path, TRUE));
} else {
$entry = array('filename' => $file, 'dirpath' => $dir);
$entry['modtime'] = filemtime($path);
do if (!is_dir($path)) {
$entry['size'] = filesize($path);
if (strstr(pathinfo($path,PATHINFO_BASENAME),'log')) {
if (!$entry['handle'] = fopen($path,r)) $entry['handle'] = "FAIL";
}
break;
} else {
break;
} while (FALSE);
$list[] = $entry;
}
}
}
closedir($handle);
return $list;
} else return FALSE;
}
$result = process_dir('C:/webserver/Apache2/httpdocs/processdir',TRUE);
foreach ($result as $file) {
if (is_resource($file['handle'])) {
echo "\n\nFILE (" . $file['dirpath'].'/'.$file['filename'] . "):\n\n" . fread($file['handle'], filesize($file['dirpath'].'/'.$file['filename']));
fclose($file['handle']);
}
}
?>