Home  >  Article  >  Backend Development  >  How Do I Get File Names from a Directory in PHP?

How Do I Get File Names from a Directory in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-10-18 18:44:29663browse

How Do I Get File Names from a Directory in PHP?

Retrieving File Names from a Directory in PHP

In PHP, obtaining the file names within a directory is a common task. Various approaches exist for achieving this.

DirectoryIterator

The recommended method is DirectoryIterator, which offers an object-oriented interface to iterate over the directory's content.

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

scandir

An alternative is scandir, which returns an array of file names.

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

opendir and readdir

Using opendir and readdir is another option.

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

glob

Glob can be employed for more complex file matching.

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

Glob allows patterns, such as using an asterisk to match any characters or specifying partial file names to filter results.

The above is the detailed content of How Do I Get File Names 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