Home >Backend Development >PHP Tutorial >PHP Master | List Files and Directories with PHP

PHP Master | List Files and Directories with PHP

Joseph Gordon-Levitt
Joseph Gordon-LevittOriginal
2025-02-25 18:23:17200browse

PHP Master | List Files and Directories with PHP

This article discusses common tasks in PHP application development: listing files and directories. We will introduce several basic and advanced solutions and analyze their pros and cons. First, we will introduce three ways to use basic PHP functions and then gradually transition to a more powerful way to leverage SPL iterators. For the sake of discussion, we assume that the directory structure is as follows:

<code>---manager
|
---user
|   ---document.txt
|   ---data.dat
|   ---style.css
|---article.txt
|---master.dat
|---script.php
|---test.dat
|---text.txt</code>

Key Points

  • PHP provides multiple functions to list files and directories, including glob(), opendir(), readdir(), closedir(), scandir(), and
  • . The flexibility of these functions varies, and some require post-filtering.
  • FilesystemIteratorStandard PHP Library (SPL) provides object-oriented solutions to list files and directories, including RecursiveDirectoryIterator, GlobIterator, and
  • . These iterators can be extended to better meet specific needs.
  • glob()opendir() Functions are a one-line solution that allows filtering, but lack flexibility. Instead, readdir(), closedir() and
  • provide greater flexibility, but require more verbose code and post-filtering.
  • scandir()GlobIterator Functions also require post-filtering, but do not require managing file handles. For object-oriented methods, the SPL library should be used. RegexIterator allows pre-filtering, while other iterators can use
  • to achieve the same functionality.

Basic Solution

glob()The first set of methods demonstrates the use of opendir() functions, the combination of readdir(), closedir() and scandir() functions, and the use of

functions.

glob()Usage

glob()The first function to be discussed is

, which allows us to search for path names using wildcards similar to the most famous shell. This function has two parameters:
  • $pattern
  • (Required): Search Mode
  • $flags
  • (Optional): One or more flags listed in the official documentation

*.txtLet's see some examples! To search for all files and directories ending with

in a directory, you can write:
<code class="language-php"><?php $filelist = glob("*.txt");</code>

$filelistIf you show

, the output will be:
<code>array (
  0 => 'article.txt',
  1 => 'text.txt'
)</code>

If you want a list of files and directories starting with "te", the code you want to write is:
<code class="language-php"><?php $filelist = glob("te*");</code>

The output is:
<code>array (
  0 => 'test.dat',
  1 => 'text.txt'
)</code>

To get only the list of directories containing "ma", the code is as follows:
<code class="language-php"><?php $filelist = glob("*ma*", GLOB_ONLYDIR);</code>

In this last example, the output is: <🎜>
<code>---manager
|
---user
|   ---document.txt
|   ---data.dat
|   ---style.css
|---article.txt
|---master.dat
|---script.php
|---test.dat
|---text.txt</code>

Note that the last example uses the GLOB_ONLYDIR constant as an optional second parameter. As you can see, a file named master.dat is excluded. Although the glob() function is easy to use, it is not flexible in some cases. For example, it has no flags to retrieve only files matching the given pattern (not directories).

Use opendir() and readdir()

The second method of reading files and directories that I want to discuss involves the opendir(), readdir() and closedir() functions. opendir() Open the directory and return to the connection handle. After the handle is retrieved, you can use readdir(). Each time this function is called, it gives the name of the next file or directory in the open directory. After all names are retrieved, the function returns false. To close the handle, you can use closedir(). Unlike glob(), this approach is a little more complicated because you don't have parameters to help you filter the returned files and directories. You have to do post-filtering yourself to get what you want. To be parallel to the glob() function, the following example retrieves a list of all files and directories starting with "te":

<code class="language-php"><?php $filelist = glob("*.txt");</code>

The output is the same as in the previous example. However, if you execute the above code and output the value of $entry at runtime, you will find that it sometimes contains some weird entries: "." and ".." . These are two virtual directories that you will find in each directory of the file system. They represent the current directory and the parent directory (the previous folder) respectively. The second example shows how to retrieve only files contained in a given path.

<code>array (
  0 => 'article.txt',
  1 => 'text.txt'
)</code>

As you might have guessed, using the above code produces the following output:

<code class="language-php"><?php $filelist = glob("te*");</code>

Usage scandir()

Finally, I want to introduce the scandir() function. It has only one required parameter: the path to read. The return value is an array of files and directories contained in the path. As with the last solution, to retrieve a subset of files and directories, you have to do post-filter yourself. On the other hand, as you can see from the code below, this solution is simpler and does not require managing file handles. This example shows how to retrieve files and directories starting with the string "te":

<code>---manager
|
---user
|   ---document.txt
|   ---data.dat
|   ---style.css
|---article.txt
|---master.dat
|---script.php
|---test.dat
|---text.txt</code>

Let's use the SPL iterator

Now let's talk about some SPL iterators. But before we dive into their use, let me introduce them and the SPL library. SPL provides a range of object-oriented data structures, iterators, file handlers, and other classes. One of the advantages is that iterators are classes, so you can extend them to better suit your needs. Another advantage is that they have very useful native methods that can help you with many common tasks you may face, and you can find them in just one place. For example, using readdir() in FilesystemIterator, both will be used in a loop, but when using readdir() your entry is just a string, and when using FilesystemIterator you have one that can give you the relevant The file or directory has a large amount of information (size, owner, permissions, etc.). Of course, PHP can use functions like filesize() and fileowner() to give you the same information, but PHP5 has turned its approach to OOP. So, all in all, my advice is to follow the new best practices of the language here. If you need more general information about SPL iterators, check Using SPL iterators. As stated in the introduction, I will show the use of FilesystemIterator, RecursiveDirectoryIterator and GlobIterator. The first inherits from DirectoryIterator, while the others inherit from FilesystemIterator. They all have the same constructor, which has only two parameters:

  • $path (Required): The path of the file system project to iterate
  • $flags (Optional): One or more flags listed in the official documentation

The actual difference between these iterators is in their way of navigating a given path.

FilesystemIterator

Using FilesystemIterator is very simple. To show how it is practical, I will show two examples. In the first example, I will search for all files and directories starting with the string "te", while the second example will use another iterator RegexIterator to search for all "t.dat" or "t. Files and directories ending with php”. RegexIterator Used to filter another iterator based on regular expressions.

<code class="language-php"><?php $filelist = glob("*.txt");</code>

Use the above code, the result is the same as in the previous example. The second example of using RegexIterator is:

<code>array (
  0 => 'article.txt',
  1 => 'text.txt'
)</code>

In this case, the output is:

<code>---manager
|
---user
|   ---document.txt
|   ---data.dat
|   ---style.css
|---article.txt
|---master.dat
|---script.php
|---test.dat
|---text.txt</code>

RecursiveDirectoryIterator

RecursiveDirectoryIterator Provides an interface for recursively iterating the file system directory. Due to its target, it has some useful methods, such as getChildren() and hasChildren(), which return the iterator for the current entry (if it is a directory) and whether the current entry is a directory. To show the practical application of RecursiveDirectoryIterator and getChildren() I will rewrite the last example to get the same result.

<code class="language-php"><?php $filelist = glob("*.txt");</code>

GlobIterator

GlobIterator Iterates over the file system in a way similar to the glob() function. Therefore, the first parameter may contain a wildcard. The following code shows common examples of using GlobIterator.

<code>array (
  0 => 'article.txt',
  1 => 'text.txt'
)</code>

Conclusion

In this article, I illustrate different ways to achieve the same goal: how to retrieve and filter files and directories in a given path. Here are some key points to remember:

  • glob() Functions are a one-line solution that allows filtering, but it is not very flexible.
  • The solutions using opendir(), readdir() and closedir() are a bit verbose and require post-filtering, but are more flexible.
  • scandir() Functions also require post-filtering, but do not require management handles.
  • If you want to use the OOP method, you should use the SPL library. Additionally, you can extend classes to suit your needs.
  • While GlobIterator is capable of pre-filtering, other iterators can use RegexIterator to achieve the same functionality in a comfortable way.

Do you know other ways to achieve this? If yes, and you want to share with us, please continue. Creative sharing is always popular. Pictures from Fotolia

FAQs (FAQ) about listing files and directories using PHP

How to sort files and directories in PHP?

The sort() can be used to sort files and directories in PHP. After retrieving files and directories using the scandir() function, you can apply the sort() function to arrange them in ascending order. If you want to sort them in descending order, you can use the rsort() function. Remember to pass the file and directory arrays as parameters to these functions.

How to exclude certain files or directories when listing files and directories in PHP?

To exclude certain files or directories, you can use the in_array() function in conjunction with the scandir() function. in_array() Function checks whether a value exists in an array. You can create an array of files or directories to exclude and use the in_array() function to check if the file or directory exists in the array. If it exists, you can skip it.

How to list directories only in PHP and not files?

To list only directories instead of files, you can use the is_dir() function. This function checks whether a path is a directory. You can use this in conjunction with the scandir() function to check if each item in the array returned by scandir() is a directory. If so, you can include it in your list.

How to recursively list files and directories in PHP?

To recursively list files and directories, you can create a recursive function that uses the scandir() function to get the files and directories and then calls itself for each directory it finds. This will allow it to traverse the entire directory tree.

How do I get the size of each file in PHP when listing a file?

To get the size of each file, you can use the filesize() function. This function returns the file size in bytes. You can use this in conjunction with the scandir() function to get the size of each file when listing it.

How do I get the last modified date of each file in PHP when listing a file?

To get the last modified date for each file, you can use the filemtime() function. This function returns the last modification time of the file as a Unix timestamp. You can use this in conjunction with the scandir() function to get the last modified date of each file when listing it.

How to filter files by extension when listing files in PHP?

To filter files by extension, you can use the pathinfo() function. This function returns information about the file path, including the extension. You can use this in conjunction with the scandir() function to filter files by extension when listing them.

How to list files and directories in remote directories in PHP?

To list files and directories in remote directories, you can use the ftp_nlist() function. This function returns a list of files and directories in the specified directory on the FTP server. Before using ftp_nlist(), you need to establish an FTP connection using the ftp_connect() and ftp_login() functions.

How to deal with errors when listing files and directories in PHP?

To handle errors when listing files and directories, you can use the error_reporting() and set_error_handler() functions. These functions allow you to set the error reporting level and define a custom error handler function that will be called when an error occurs.

How to list files and directories in ZIP archives in PHP?

To list files and directories in a ZIP archive, you can use the ZipArchive class. This class provides methods for handling ZIP archives, including the getFromName() method, which allows you to retrieve the contents of files in the archive.

The above is the detailed content of PHP Master | List Files and Directories with PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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