Created
March 14, 2012 15:43
-
-
Save nertim/2037367 to your computer and use it in GitHub Desktop.
Using PHP to get a list of files from a directory and all its subdirectories
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* A little helper function get all file names from a directory. | |
*/ | |
function testFiles() { | |
//Initialize a starting point | |
$path = getcwd() . "/public/images"; | |
$filesArr = array(); | |
$this->getFiles($path, $filesArr); | |
print_r($filesArr); | |
} | |
/** | |
* Recursive function to get list of all files including from subdirs for a given directory | |
* | |
* @param string $path path to explore the files from | |
* @param array &$filesArr pass by reference variable to push files to the array | |
* @param bool $includePath if set to true the entire path for the path is included, else just the filename | |
*/ | |
function getFiles($path, &$filesArr, $includePath = false) { | |
if ($handle = opendir($path)) { | |
while (false !== ($entry = readdir($handle))) { | |
if ($entry != "." && $entry != "..") { | |
$currentPath = $path."/{$entry}"; | |
//if the current path is a directory, recall the getFiles function and get | |
//all the files from this directory | |
if (is_dir($currentPath)) { | |
$this->getFiles($currentPath, $filesArr, $includePath); | |
} else { | |
$pathParts = pathinfo($currentPath); | |
//save off files that contain an extension | |
if (isset($pathParts['extension']) && strlen($pathParts['extension']) > 0) { | |
$entry = ($includePath) ? $currentPath : $entry; | |
$filesArr[] = $entry; | |
} | |
} | |
} | |
} | |
closedir($handle); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment