Home >Backend Development >PHP Tutorial >How to Fetch File Names Within a Directory in PHP

How to Fetch File Names Within a Directory in PHP

Patricia Arquette
Patricia ArquetteOriginal
2024-10-18 18:42:03208browse

How to Fetch File Names Within a Directory in PHP

Fetching File Names Within a Directory in PHP

In PHP, acquiring the file names within a directory requires specific commands. Having exhausted search engines, this question explores the various methods available for this task.

Approaches

1. DirectoryIterator (Recommended)

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

2. scandir

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

3. opendir and readdir

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

4. glob

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

Additional Note on glob

Glob offers a unique advantage over other methods. The asterisk (*) wildcard can be used for matching files based on criteria. For instance, glob('*.txt') retrieves all text files in the directory, while glob('image_*') fetches files starting with "image_".

The above is the detailed content of How to Fetch File Names Within 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