List txt files php

List Files and Directories with 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.

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() .

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:

  • $pattern (mandatory): The search pattern
  • $flags (optional): One or more flags as listed in the official documentation

Let’s see some examples! To search in the directory for all files and directories that end with .txt, you would write:

If you display $filelist , the output will be:

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:

array ( 0 => 'test.dat', 1 => 'text.txt' )

To get a list of directories only which contain “ma”, the code is:

In this last example, the output is:

Notice that the last example makes use of the GLOB_ONLYDIR constant as the optional second parameter. As you can see, the file called master.dat is excluded because of it. Although the glob() function is easy to use, it isn’t so flexible sometimes. For example, it doesn’t have a flag to retrieve only files (and not directories) that match a given pattern.

Using opendir() and readdir()

The second approach to read files and directories I’d like to discuss involves the functions opendir() , readdir() , and closedir() .

opendir() opens the directory and returns a connection handle. Once the handle is retrieved, you can use readdir() . With each invocation, this function will give the name of the next file or directory inside an opened directory. When all the names have been retrieved, the function returns false. To close the handle you use closedir() .

Unlike glob() , this approach is a bit more involved since you don’t have parameters that help you filter the returned files and the directories. You have to perform post-filtering yourself to get what you want.

To parallel with the glob() function, the following example retrieves a list of all the files and the directories that start with “te”:

Читайте также:  Php вывести элемент объекта

The output is the same as the previous example.

But if you execute the code above and output the value of $entry as it runs, you’ll see it contains some odd-looking entries at times: “.” and “..”. These are two virtual directories you’ll find in each directory of the file system. They represent the current directory and the parent directory (the up-level folder) respectively.

The second example shows how to retrieve only the files contained in a given path.

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

array ( 0 => 'article.txt', 1 => 'master.dat', 2 => 'script.php', 3 => 'test.dat', 4 => 'text.txt' )

Using scandir()

And finally, I’d like to present the scandir() function. It has only one mandatory parameter: the path to read. The value returned is an array of the files and directories contained in the path. Just like the last solution, to retrieve a subset of files and directories, you have to do post-filtering yourself. On the other hand, as you can see by looking at the code below, this solution is more concise and doesn’t need to manage file handle.

This example shows how to retrieve files and directories which start with the string “te”:

Let’s use the SPL Iterators

Now let’s talk about some SPL Iterators. But before going into deep about their use, let me introduce them and the SPL library. The SPL provides a series of classes for object-oriented data structures, iterators, file handlers, and other features.

One of the pros is that Iterators are classes and so you can extend them to better fit your needs. Another advantage is that they have native methods that are really helpful in achieving many of the common task you might face and you have them in just one place. Take as an example the use of FilesystemIterator among readdir() , both of them will be used in a loop but while using readdir() your entry will be nothing but a string, using FilesystemIterator you have an object that can provide you a lot of information about that file or directory (size, owner, permissions and so on).

Of course, PHP can provide you the same information using functions like filesize() and fileowner() but PHP5 has turned its approach to OOP. So, in conclusion, my advice here is to follow the new best practices for the language. In case you need more general information about SPL Iterators, take a look at Using SPL Iterators.

As said in the introduction, I’ll show the use of FilesystemIterator , RecursiveDirectoryIterator and GlobIterator . The first of them inherits from the DirectoryIterator while the others inherit from the FilesystemIterator . They all have the same constructor which has just two parameters:

  • $path (mandatory): The path of the filesystem item to be iterated over
  • $flags (optional): One or more flags as listed in the official documentation
Читайте также:  Birthday Reminders for August

What actually differs in these iterators is the approach they use to navigate the given path.

The FilesystemIterator

Using the FilesystemIterator is quite simple. To see it in action, I’ll show two examples. In the first, I’ll search for all the files and directories which start with the string “te” while the second will use another iterator, the RegexIterator , to search all the files and directories that contains ends with “t.dat” or “t.php”. The RegexIterator is used to filter another iterator based on a regular expression.

getFilename(), "te") === 0) < $filelist[] = $entry->getFilename(); > >

With the code above, the result is the same of the previous examples.

The second example that uses the RegexIterator is:

In this case the output is:

array ( 0 => 'script.php', 1 => 'test.dat' )

The RecursiveDirectoryIterator

The RecursiveDirectoryIterator provides an interface for iterating recursively over filesystem directories. Due to its aim, it has some useful methods as getChildren() and hasChildren() which returns an iterator for the current entry if it is a directory and whether current entry is a directory respectively. To see both RecursiveDirectoryIterator and the getChildren() in action, I’ll rewrite the last example to get the same result.

getChildren(), '/t.(php|dat)$/'); $filelist = array(); foreach($filter as $entry) < $filelist[] = $entry->getFilename(); >

The GlobIterator

The GlobIterator iterates through the file system in a similar way to the glob() function. So the first parameter can include wildcards. The code below shows the usual example with the use of the GlobIterator .

Conclusions

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

  • The function glob() is a one-line solution and allows filtering, but it isn’t very flexible.
  • The solution using opendir() , readdir() , and closedir() is a bit verbose and needs a post-filtering but is more flexible.
  • The function scandir() requires post-filtering as well but doesn’t need to manage the handle.
  • If you want to use an OOP approach, you should use the SPL library. Moreover you can extend the classes to fit your needs.
  • While the GlobIterator has the ability to do pre-filtering, the others can do the same in a comfortable way using the RegexIterator .

Do you know of other approaches to achieve the goal? If so and you want to share with us, go ahead. Knowledge sharing is always welcome.

Share This Article

I’m a (full-stack) web and app developer with more than 5 years’ experience programming for the web using HTML, CSS, Sass, JavaScript, and PHP. I’m an expert of JavaScript and HTML5 APIs but my interests include web security, accessibility, performance, and SEO. I’m also a regular writer for several networks, speaker, and author of the books jQuery in Action, third edition and Instant jQuery Selectors .

Источник

How to List Files in a Directory in PHP

Sajal Soni

Sajal Soni Last updated Aug 31, 2021

Читайте также:  Https bk sovcombank ru html login html

In this article, we’ll discuss how you can get a list of all the files in a directory in PHP.

In your day-to-day PHP development, you often need to deal with a file system—for example, getting a list of files in a specific directory. PHP provides a few different ways of reading the contents of a directory easily. Today, we’ll go through all these methods, along with examples to understand how each one works.

The opendir , readdir , and closedir Functions

In this section, we’ll discuss the opendir , readdir , and closedir functions to see how you can use them to get a list of files in a specific directory.

The opendir function allows you to open up a directory handle, which you can use along with other functions for different operations on the directory. You need to pass the path to the directory in the first argument of the opendir function. If the directory path is valid, a directory handle resource will be returned.

The readdir function allows you to read a directory. You need to provide a valid directory handle in the first argument of the readdir function, and you can iterate over all the entries and get a list of all files in a directory.

The closedir function allows you to close the directory handle which is opened by the opendir function. It’s a good practice to use the closedir function once you’re done with your operations on the directory handle (which was initially opened by the opendir function).

Now, let’s see it in action in the following example.

Источник

PHP: List all files in a directory.

In this beginner’s tutorial, I will show you how to list all files in a directory using PHP. We will do this using PHP’s glob function, which allows us to retrieve a list of file pathnames that match a certain pattern.

For this example, I have created a folder called “test”. Inside the folder, I have created three files:

Here is a screenshot of the directory:

Directory

In our first PHP code snippet, we will simply list everything that is in the test folder:

The result will look something like this:

test/file.php test/names.txt test/test.txt

However, what if we wanted to list all files with a particular file extension? i.e. What if we only want to list the .txt files and not the .php file that is currently present?

Well, the solution is pretty simple:

//Get a list of all files ending in .txt $fileList = glob('test/*.txt');

In the code snippet above, we told the glob function to return a list of file pathnames that ended .txt

Warning: In some cases, the folder may have subdirectories. In cases where you are listing everything that is inside a specified folder, these subdirectories will be returned by the glob function. To avoid printing out or interacting with subdirectories, you can simply use the is_file function to confirm that the file pathname in question leads to an actual file:

Hopefully, this tutorial was useful!

Источник

Оцените статью