Home > php教程 > php手册 > PHP 获取指定目录下所有文件(包含子目录),

PHP 获取指定目录下所有文件(包含子目录),

WBOY
Release: 2016-06-13 08:44:59
Original
1331 people have browsed it

PHP 获取指定目录下所有文件(包含子目录),

PHP 获取指定目录下所有文件(包含子目录)

测试环境在linux下,如果要在windows,请改正$new_dir中的目录路径查找方式

<?<span>php
 
function get_file_list($dir)
{
  </span><span>
    $file_list </span>=<span> array();
    $file_dir_list </span>=<span> array();
     
    $dir_list </span>= scandir($dir); <span>//</span><span>查找目录  </span>
     
    <span>foreach</span> ($dir_list <span>as</span><span> $r)
    {
        </span><span>if</span> ($r == <span>'</span><span>.</span><span>'</span> || $r == <span>'</span><span>..</span><span>'</span><span>)  
        {
            </span><span>continue</span><span>;
        }
        $new_dir </span>= $dir . <span>'</span><span>/</span><span>'</span><span> . $r;
        </span><span>if</span><span> (is_dir($new_dir))
        {</span><span>
            $file_dir </span>=<span> get_file_list($new_dir);
            $file_dir_list </span>=<span> array_merge($file_dir_list, $file_dir);
        }
        </span><span>else</span><span>
        {
            $file_list[] </span>=<span> $new_dir;
        }
    }
     
    </span><span>return</span><span> array_merge($file_list, $file_dir_list);
}
 
$file_list </span>= get_file_list(<span>'</span><span>.</span><span>'</span><span>);
print_r($file_list);</span>
Copy after login

scandir定义和用法

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

若成功,则返回一个数组,若失败,则返回 false。如果 directory 不是目录,则返回布尔值 false 并生成一条 E_WARNING 级的错误。

语法

scandir(directory,sort,context)
Copy after login
参数描述
directory 必需。规定要扫描的目录。
sort 可选。规定排列顺序。默认是 0 (升序)。如果是 1,则为降序。
context 可选。规定目录句柄的环境。context 是可修改目录流的行为的一套选项。

例子

<?<span>php
print_r(scandir(</span><span>"</span><span>images</span><span>"</span><span>));
</span>?> 
Copy after login

输出:

<span>Array
(
[</span><span>0</span>] =><span> .
[</span><span>1</span>] =><span> ..
[</span><span>2</span>] =><span> dog.jpg
[</span><span>3</span>] =><span> house.jpg
[</span><span>4</span>] =><span> logo.gif
)</span>
Copy after login

 

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