Last active
December 2, 2017 04:54
-
-
Save brucekirkpatrick/8528710 to your computer and use it in GitHub Desktop.
Function to return only the files in a directory, and optionally do this recursively.
This file contains hidden or 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 | |
function getFilesInDirectoryAsArray($directory, $recursive, $arrFilter=array()) { | |
$arrItems = array(); | |
if(substr($directory, strlen($directory)-1, 1) != "/"){ | |
$directory.="/"; | |
} | |
if(count($arrFilter)){ | |
$filterMap=array(); | |
for($i=0;$i<count($arrFilter);$i++){ | |
$filterMap[$arrFilter[$i]]=true; | |
} | |
var_dump($filterMap); | |
recurseDirectoryWithFilter($arrItems, $directory, $recursive, $filterMap); | |
}else{ | |
recurseDirectory($arrItems, $directory, $recursive); | |
} | |
return $arrItems; | |
} | |
function recurseDirectory(&$arrItems, $directory, $recursive) { | |
if ($handle = opendir($directory)) { | |
while (false !== ($file = readdir($handle))) { | |
if ($file != "." && $file != "..") { | |
if(is_dir($directory.$file)) { | |
if($recursive){ | |
recurseDirectory($arrItems, $directory.$file."/", $recursive); | |
} | |
}else{ | |
$arrItems[] = $directory . $file; | |
} | |
} | |
} | |
closedir($handle); | |
} | |
return $arrItems; | |
} | |
function recurseDirectoryWithFilter(&$arrItems, $directory, $recursive, &$filterMap) { | |
if ($handle = opendir($directory)) { | |
while (false !== ($file = readdir($handle))) { | |
if ($file != "." && $file != "..") { | |
if(is_dir($directory.$file)) { | |
if($recursive){ | |
recurseDirectoryWithFilter($arrItems, $directory.$file."/", $recursive, $filterMap); | |
} | |
}else{ | |
if(isset($filterMap[getFileExt($file)])){ | |
$arrItems[] = $directory . $file; | |
} | |
} | |
} | |
} | |
closedir($handle); | |
} | |
return $arrItems; | |
} | |
function getFileExt($path){ | |
$pos=strrpos($path, "."); | |
if($pos===FALSE){ | |
return ""; | |
}else{ | |
return substr($path, $pos+1); | |
} | |
} | |
?> |
Added support to filter the files by one or more file extensions. Usage: var_dump(getFilesInDirectoryAsArray("/path/",true, array("js", "css")));
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use like this: var_dump(getFilesInDirectoryAsArray("/path/",true));