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

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

Susan Sarandon
Release: 2024-10-18 18:44:29
Original
756 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

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