php列出目录文件_用PHP列出文件和目录

本文详细介绍了使用PHP列出目录文件的各种方法,包括glob()、opendir()和readdir()、scandir(),以及使用SPL迭代器如FilesystemIterator、RecursiveDirectoryIterator和GlobIterator。文章通过实例展示了如何过滤和获取指定路径下的文件和目录,强调了不同方法的灵活性和适用场景。
摘要由CSDN通过智能技术生成

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值