Php listing directory contents

PHP: Directory Listing

A common request is to be able to produce a list of some or all of the files in a directory — similar to the default index page provided by most web servers, but with more control over the content and formatting.

Another goal might be to take some action on the files using PHP. In either case the first step is to query the file system to return a list of directories and files.

The functions presented below provide the means to extract the file names and other properties from a single directory, or to explore subdirectories recursively.

PHP 5 introduces the scandir function which will «List files and directories inside the specified path» but won’t recurse or provide additional information about the listed files.

If you are using PHP 5 or higher check out our new article on Directory Listing using SPL classes for a much neater approach, and our new FileList PHP class.

Single Directory Listing

To get started, here is a simple function that returns a list of files, directories and their properties from a single directory (more advanced versions of this function can be found further down the page):

You can use this function as follows:

The variable $_SERVER['DOCUMENT_ROOT'] should resolve to the root directory of your website. e.g. /var/www/public_html

The return value is an associative array of files including the filepath, type, size and last modified date, except when a file is actually a directory, in that case the string «(dir)» appears instead of the filesize. The filenames take the same stem as the function call:

«,print_r($dirlist),»

«; /* sample output Array ( [0] => Array ( [name] => images/background0.jpg [type] => image/jpeg [size] => 86920 [lastmod] => 1077461701 ) [1] => . ) */ ?>

«,print_r($dirlist),»

«; /* sample output Array ( [0] => Array ( [name] => ./ images/background0.jpg [type] => image/jpeg [size] => 86920 [lastmod] => 1077461701 ) [1] => . ) */ ?>

If you want the output sorted by one or more fields, you should read the article on Sorting Arrays of Arrays or try out one of our DHTML Sorting Algorithms using JavaScript.

Читайте также:  Php оператор if строки

We also have an article on Directory Listing using SPL classes (DirectoryIterator and SplFileInfo) which introduces many new options for filtering and sorting the output.

Displaying File List in HTML

To output the results to an HTML page we just loop through the returned array:

// output file list in HTML TABLE format echo «

\n»; echo « \n»; echo «

\n»; echo «

\n»; echo «

\n»; foreach($dirlist as $file) < echo " \n»; echo »

\n»; echo «

\n»; > echo «

\n»; echo «

Name Type Size Last Modified
\n»; echo » \n»; echo » \n»; echo « «,date(‘r’, $file[‘lastmod’]),»

\n\n»; ?>

This code can be easily modified to: make the output a list instead of a table; make the file names actual links; replace the names with icons based on file type or extension; etc.

Display PNG images in a TABLE:

For example, to display only PNG files, just add a condition to the output loop:

// output file list as HTML table echo «

\n»; echo « \n»; echo »

\n»; echo «

\n»; echo «

\n»; foreach($dirlist as $file) < if(!preg_match("/\.png$/", $file['name'])) < continue; >echo « \n»; echo «

\n»; echo »

\n»; echo «

\n»; > echo «

\n»; echo «

&lt/th> Name Type Size Last Modified
\» width=\»64\» alt=\»\»> \n»; echo » \n»; echo » \n»; echo « «,date(‘r’, $file[‘lastmod’]),»

\n\n»; ?>

Here you can view the complete source code for this example.

This will have the effect of skipping all files whose name does not end with .png. You could also apply conditions based on the file type, size, or last modified timestamp.

One last example, listing only PDF files and having the file name link to the file:

// output file list as table rows foreach($dirlist as $file) < if($file['type'] != 'application/pdf') < continue; >echo « \n»; echo »

\n»; echo »

\n»; echo «

\n»; > ?>

Name Type Size Last Modified
\»>»,basename($file[‘name’]),» \n»; echo » \n»; echo « «,date(‘r’, $file[‘lastmod’]),»

Here you can view the complete source code for this example.

If you want to display, for example, a thumbnail as a link to a larger image, or even a video, just give the two files the same name and in the script above use str_replace or similar function to modify either the link href or the link contents. See our article on listing images for examples.

Using the SPL DirectoryIterator and FilterIterator classes we can now specify a pattern to match when accessing the file list so only matching files are returned. More on that here.

Recursive Directory Listing

Now that we’ve got this far, it’s only a minor change to extend the function in order to recursively list subdirectories. By adding a second parameter to the function we also retain the previous functionality of listing a single directory.

To make use of the new functionality, you need to pass a value of TRUE (or 1) as the second parameter.

Before recursing the script first checks whether sub-directories are readable, and otherwise moves on to the next item so as to avoid permission errors.

As before, the return value is an array of associative arrays. In fact the only change is that you have the additional option of a recursive listing.

Limited Depth Recursion

This final example adds another feature — the ability to specify how deep you want the recursion to go. The previous code would continue to explore directories until it ran out of places to go. With this script you can tell it to not go deeper than a fixed number of levels in the file system.

As before we’ve added a single new parameter and a few lines of code. The default value of the depth parameter, if not defined in the function call, is set to FALSE. This ensures that all previous features remain and that any legacy code won’t break when the function is changed.

In other words, we can now call the getFileList function with one, two or three parameters:

This is a good example of how a function can evolve over time without becoming unmanageable. Too often you see functions that were once useful become unusable because of parameter bloat.

Fileinfo replaces mime_content_type

The mime_content_type function has been deprecated in recent version of PHP and replaced with the PECL Fileinfo extension was never actually deprecated, despite announcements to the contrary.

If you are seeing errors in your program due to this, the following patch should work:

This is the same function as seen at the top of the page, just with a check for the mime_content_type function inserted at the top to determine which method we use to get the file type.

If you are scanning a complex directory system you probably want to declare $finfo as a global variable to avoid having to re-instantiate it when the function recurses.

References

Источник

How to List Files in a Directory in PHP

Sajal Soni

Sajal Soni Last updated Aug 31, 2021

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.

Источник

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