Home  >  Article  >  Backend Development  >  How to List Files with Specific Extensions in a PHP Directory?

How to List Files with Specific Extensions in a PHP Directory?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-17 02:13:03118browse

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!

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