PHP scandir() 但排除某些文件夹
PHP scandir() but exclude certain folders
我在下面的 Whosebug 上找到了这个函数,但是,我试图避免扫描名称为 includes.
的任何目录
$dir = $_SESSION['site'];
function getDirContents($dir, &$results = array()){
$files = scandir($dir);
foreach ($files as $key => $value) {
$path = realpath($dir.DIRECTORY_SEPARATOR.$value);
if (!is_dir($path)) {
$results[] = $path;
} else if (is_dir($path) && $value != "." && $value != ".." ) {
getDirContents($path, $results);
$results[] = $path;
}
}
return $results;
}
我尝试添加一个额外的 &&
如下:
} else if (is_dir($path) && $value != "." && $value != ".." && !strstr($path,"includes/")) {
然而,这似乎并不能解决问题。
I am trying to avoid scanning any directory with the name "includes".
您可以尝试更换
$files = scandir($dir);
和
$files = preg_grep("/includes/i", scandir($dir), PREG_GREP_INVERT);
这将导致 $files
的数组不包含字符串 "includes" 使用 preg_grep 和反向匹配。
If set to PREG_GREP_INVERT, this function returns the elements of the input array that do not match the given pattern (ref).
作为奖励,您可以轻松自定义正则表达式以添加更多排除的路径。示例:
"/includes|admin|hidden|temp|cache|^\./i"
这也将排除以 .
开头的目录,因此您可以减少一些逻辑。
另一个选择是
$files = preg_grep('/^((?!includes).)*$/i', scandir($dir));
这将导致 $files
的数组不包含字符串 "includes"。它使用 preg_grep 和 否定环视 来检查 "includes",如果未找到,则该路径包含在最终数组中。
只需删除尾部斜杠:
!strstr($path,"includes")) {
我在下面的 Whosebug 上找到了这个函数,但是,我试图避免扫描名称为 includes.
$dir = $_SESSION['site'];
function getDirContents($dir, &$results = array()){
$files = scandir($dir);
foreach ($files as $key => $value) {
$path = realpath($dir.DIRECTORY_SEPARATOR.$value);
if (!is_dir($path)) {
$results[] = $path;
} else if (is_dir($path) && $value != "." && $value != ".." ) {
getDirContents($path, $results);
$results[] = $path;
}
}
return $results;
}
我尝试添加一个额外的 &&
如下:
} else if (is_dir($path) && $value != "." && $value != ".." && !strstr($path,"includes/")) {
然而,这似乎并不能解决问题。
I am trying to avoid scanning any directory with the name "includes".
您可以尝试更换
$files = scandir($dir);
和
$files = preg_grep("/includes/i", scandir($dir), PREG_GREP_INVERT);
这将导致 $files
的数组不包含字符串 "includes" 使用 preg_grep 和反向匹配。
If set to PREG_GREP_INVERT, this function returns the elements of the input array that do not match the given pattern (ref).
作为奖励,您可以轻松自定义正则表达式以添加更多排除的路径。示例:
"/includes|admin|hidden|temp|cache|^\./i"
这也将排除以 .
开头的目录,因此您可以减少一些逻辑。
另一个选择是
$files = preg_grep('/^((?!includes).)*$/i', scandir($dir));
这将导致 $files
的数组不包含字符串 "includes"。它使用 preg_grep 和 否定环视 来检查 "includes",如果未找到,则该路径包含在最终数组中。
只需删除尾部斜杠:
!strstr($path,"includes")) {