Home >Backend Development >PHP Tutorial >How to Retrieve Filenames from a Directory in PHP?

How to Retrieve Filenames from a Directory in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-18 18:43:29487browse

How to Retrieve Filenames from a Directory in PHP?

Retrieve Files from a Directory in PHP

How can I access the filenames within a directory in PHP? Identifying the proper command has proven challenging. This question aims to provide assistance to individuals seeking similar solutions.

PHP offers several methods for obtaining file listings from a directory:

DirectoryIterator (Recommended)

This class allows for the iteration over files in a directory:

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

scandir

This function retrieves an array of files and directories in a directory:

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

readdir and opendir

This combination of functions provides access to a directory handle:

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

glob

This function is useful for matching files based on patterns:

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

Additional Notes

glob allows for more complex file matching using patterns, such as ''.txt' for text files or 'image_' for files starting with the prefix 'image_'.

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