Home > php教程 > php手册 > body text

使用PHP函数scandir排除特定目录

WBOY
Release: 2016-06-13 09:33:53
Original
817 people have browsed it

scandir()函数返回一个数组,其中包含指定路径中的文件和目录。如下所示:

例子:

复制代码 代码如下:

print_r(scandir('test_directory'));
?>


输出:

复制代码 代码如下:

Array
(
[0]=>.
[1]=>..
[2]=>1.txt
[3]=>2.txt
)


大部分情况只需要该目录的文件列表数组,如下:

复制代码 代码如下:

Array
(
[0]=>1.txt
[1]=>2.txt
)


一般是通过排除“.”或者“..”的数组项解决的:

复制代码 代码如下:

functionfind_all_files($dir)
{
    $root = scandir($dir);
    foreach($rootas$value)
    {
        if($value === '.' || $value === '..'){
            continue;
        }
        if(is_file("$dir/$value")){
            $result[] = "$dir/$value";
            continue;
        }
        foreach(find_all_files("$dir/$value")as$value)
        {
            $result[] = $value;
            }
        }
    return$result;
    }
?>


另外一种方法,利用array_diff函数,剔除scandir函数执行得到的数组:

复制代码 代码如下:

$directory='/path/to/my/directory';
$scanned_directory=array_diff(scandir($directory),array('..','.'));
?>


通常情况代码管理会产生.svn文件,或者限制目录访问权限的.htaccess等文件。所以通过array_diff函数来过滤会更方便。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!