Home >Backend Development >PHP Tutorial >How to Fetch 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.
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!