This function takes in a directory path and recursively searches through the directory structure and returns all files in those directories. The file list is returned in an array.
This function has 1 required parameter and 2 optional parameters.
directoryToArray(Path to Directory [,file extention [,Display Full Path]]
If the file extension parameter is set, only files matching that extension will be displayed, ie, "jpg"
If the Display Full Path parameter is true, then the full path of the file will be returned. If it is false, only the file name will be returned. By default, this parameter is set to true.
function directoryToArray($directory, $extension="", $full_path = true) {
$array_items = array();
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if (is_dir($directory. "/" . $file)) {
$array_items = array_merge($array_items, directoryToArray($directory. "/" . $file, $extension, $full_path));
}
else {
if(!$extension || (ereg("." . $extension, $file)))
{
if($full_path) {
$array_items[] = $directory . "/" . $file;
}
else {
$array_items[] = $file;
}
}
}
}
}
closedir($handle);
}
return $array_items;
}
This is a nice snippet but a a minor change that could improve it a bit. The extension could be treated differently so you can specify no extension and only grab files with no extensions. Would be easy to do like this:
function directoryToArray($directory, $extension = false, $full_path = true) {
if ($extension !== false && strlen($extension)) { $extension = \"\.$extension\"; }
And the if statement that checks for a condition:
if($extension !== false || (ereg(\"$extension\$\", $file)))
Then leaving an empty string would return all files with no extensions, or specifying false (or leaving it empty) will return all files.