Home >Backend Development >PHP Tutorial >How to List Files with Specific Extensions in a PHP Directory?
PHP: Listing Specific Files in a Directory
Introduction
The given PHP code serves the purpose of listing files within a directory, providing a basic list of all files present. However, a need arises to refine this list by displaying only files with a specific extension, such as ".xml" or ".XML."
Solution
To list files with a particular extension, the glob() function comes to our aid. This function searches for pathnames matching a given pattern.
Code
$files = glob('/path/to/dir/*.xml');
In this example, we use the glob() function to search for files that end with ".xml" within the specified directory. The $files variable will now hold an array containing the paths of the matching files.
Usage
To display these files in an HTML list, you can modify the original code as follows:
if ($handle = opendir('.')) { while (false !== ($file = readdir($handle))) { if (($file != ".") && ($file != "..") && (substr($file, -4) == ".xml")) { $thelist .= '<LI><a href="'.$file.'">'.$file.'</a>'; } } closedir($handle); } ?> <P>List of .xml files:</p> <UL> <P><?=$thelist?></p> </UL>
This updated code ensures that only files with the ".xml" extension are displayed in the list.
The above is the detailed content of How to List Files with Specific Extensions in a PHP Directory?. For more information, please follow other related articles on the PHP Chinese website!