How Can I Retrieve Filenames from a Directory in PHP?

Barbara Streisand
Release: 2024-10-18 18:40:04
Original
919 people have browsed it

How Can I Retrieve Filenames from a Directory in PHP?

Obtaining Filenames from a Directory Using PHP

Many PHP developers seek a reliable method to retrieve the file names within a directory. This comprehensive guide explores multiple approaches for achieving this task.

DirectoryIterator: The Preferred Choice

PHP's DirectoryIterator class offers an optimized solution:

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

Scandir: An Alternative Route

Scandir provides a simpler option:

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

Opendir and Readdir: Legacy Option

For legacy code compatibility:

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

Glob: Powerful Pattern Matching

Glob offers a versatile approach with pattern matching:

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

Note that using "" in glob allows for customizable patterns (e.g., "glob('.txt')" retrieves text files).

The above is the detailed content of How Can I 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