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>
glob()
, opendir()
, readdir()
, closedir()
, scandir()
, and FilesystemIterator
Standard PHP Library (SPL) provides object-oriented solutions to list files and directories, including RecursiveDirectoryIterator
, GlobIterator
, and glob()
opendir()
Functions are a one-line solution that allows filtering, but lack flexibility. Instead, readdir()
, closedir()
and 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
glob()
The first set of methods demonstrates the use of opendir()
functions, the combination of readdir()
, closedir()
and scandir()
functions, and the use of
glob()
Usage
glob()
The first function to be discussed is
$pattern
$flags
*.txt
Let's see some examples! To search for all files and directories ending with
<?php $filelist = glob("*.txt");
$filelist
If you show
<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:
<?php $filelist = glob("te*");
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:
<?php $filelist = glob("*ma*", GLOB_ONLYDIR);
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).
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":
<?php $filelist = glob("*.txt");
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:
<?php $filelist = glob("te*");
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>
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.
<?php $filelist = glob("*.txt");
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.
<?php $filelist = glob("*.txt");
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>
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. 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. 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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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!