PHP: Get Files in a Directory Recursively
This is a method that will return an array of file paths from a directory. It’s contained within CrayonUtil and calls other utility methods in that class, but can be ripped out if needed.
/** * @param $path A directory * @param array $args Argument array: * hidden: If true, hidden files beginning with a dot will be included * ignoreRef: If true, . and .. are ignored * recursive: If true, this function is recursive * ignore: An array of paths to ignore * @return array Files in the directory */ public static function getFiles($path, $args = array()) { $hidden = self::set_default($args['hidden'], TRUE); $ignoreRef = self::set_default($args['ignoreRef'], TRUE); $recursive = self::set_default($args['recursive'], FALSE); $ignore = self::set_default($args['ignore'], NULL); $ignore_map = array(); if ($ignore) { foreach ($ignore as $i) { if (is_dir($i)) { $i = CrayonUtil::path_slash($i); } $ignore_map[$i] = TRUE; } } $files = glob($path . '*', GLOB_MARK); if ($hidden) { $files = array_merge($files, glob($path . '.*', GLOB_MARK)); } if ($ignoreRef || $ignore) { $result = array(); for ($i = 0; $i < count($files); $i++) { $file = $files[$i]; if (!isset($ignore_map[$file]) && (!$ignoreRef || (basename($file) != '.' && basename($file) != '..'))) { $result[] = $file; if ($recursive && is_dir($file)) { $result = array_merge($result, self::getFiles($file, $args)); } } } } else { $result = $files; } return $result; }