Home > Backend Development > PHP Tutorial > 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
Release: 2024-11-17 02:13:03
Original
197 people have browsed it

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');
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template