How to Retrieve Filenames from a Directory in PHP?

Patricia Arquette
Release: 2024-10-18 18:43:29
Original
341 people have browsed it

How to Retrieve Filenames from a Directory in PHP?

Retrieve Files from a Directory in PHP

How can I access the filenames within a directory in PHP? Identifying the proper command has proven challenging. This question aims to provide assistance to individuals seeking similar solutions.

PHP offers several methods for obtaining file listings from a directory:

DirectoryIterator (Recommended)

This class allows for the iteration over files in a directory:

<code class="php">foreach (new DirectoryIterator('.') as $file) {
    if($file->isDot()) continue;
    print $file->getFilename() . '<br>';
}</code>
Copy after login

scandir

This function retrieves an array of files and directories in a directory:

<code class="php">$files = scandir('.');
foreach($files as $file) {
    if($file == '.' || $file == '..') continue;
    print $file . '<br>';
}</code>
Copy after login

readdir and opendir

This combination of functions provides access to a directory handle:

<code class="php">if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if($file == '.' || $file == '..') continue;
        print $file . '<br>';
    }
    closedir($handle);
}</code>
Copy after login

glob

This function is useful for matching files based on patterns:

<code class="php">foreach (glob("*") as $file) {
    if($file == '.' || $file == '..') continue;
    print $file . '<br>';
}</code>
Copy after login

Additional Notes

glob allows for more complex file matching using patterns, such as ''.txt' for text files or 'image_' for files starting with the prefix 'image_'.

The above is the detailed content of How to Retrieve Filenames from a Directory in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!