Home  >  Article  >  Backend Development  >  How Can I Retrieve Filenames from a Directory in PHP?

How Can I Retrieve Filenames from a Directory in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-10-18 18:40:04925browse

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>

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>

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>

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>

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!

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