php列出目录文件
In this article I’ll talk about a common task you might have experienced while developing a PHP application: listing files and directories. I’ll discuss several basic and advanced solutions, each having its pros and cons. First I’ll present three approaches that use some very basic PHP functions and then progress to more robust ones which make use of SPL Iterators.
在本文中,我将讨论您在开发PHP应用程序时可能会遇到的常见任务:列出文件和目录。 我将讨论几种基本和高级解决方案,每种解决方案都有其优缺点。 首先,我将介绍三种使用一些非常基本PHP函数的方法,然后逐步介绍使用SPL迭代器的更可靠的方法。
For the purposes of the discussion, let’s assume a directory structure that looks like the one below:
为了便于讨论,我们假设一个目录结构如下所示:
---manager
|
---user
| ---document.txt
| ---data.dat
| ---style.css
|---article.txt
|---master.dat
|---script.php
|---test.dat
|---text.txt
基本解决方案 (The Basic Solutions)
The first set of approaches demonstrate the use of the functions glob()
, a combination of the functions opendir()
, readdir()
and closedir()
, and the the function scandir()
.
第一组方法演示了功能glob()
,功能opendir()
, readdir()
和closedir()
以及功能scandir()
。
使用glob() (Using glob())
The first function to discuss is glob()
which allows us to perform a search for pathnames using wildcards common to the best known shells. The function has two parameters:
讨论的第一个函数是glob()
,它使我们能够使用众所周知的Shell通用的通配符来搜索路径名。 该函数有两个参数:
$pattern
(mandatory): The search pattern$pattern
(强制性):搜索模式$flags
(optional): One or more flags as listed in the official documentation$flags
(可选): 官方文档中列出的一个或多个标志
Let’s see some examples! To search in the directory for all files and directories that end with .txt, you would write:
让我们看一些例子! 要在目录中搜索所有以.txt结尾的文件和目录,应编写:
<?php
$filelist = glob("*.txt");
If you display $filelist
, the output will be:
如果显示$filelist
,输出将是:
array (
0 => 'article.txt',
1 => 'text.txt'
)
If you want a list of files and directories that begin with “te”, the code to write is:
如果要以“ te”开头的文件和目录的列表,要编写的代码是:
<?php
$filelist = glob("te*");
The output is:
输出为:
array (
0 => 'test.dat',
1 => 'text.txt'
)
To get a list of directories only which contain “ma”, the code is:
要获取仅包含“ ma”的目录列表,代码为:
<?php
$filelist = glob("*ma*", GLOB_ONLYDIR);
In this last example, the output is:
在最后一个示例中,输出为:
array (
0 => 'manager'
)
Notice that the last