Obtaining Filenames from a Directory Using PHP
Many PHP developers seek a reliable method to retrieve the file names within a directory. This comprehensive guide explores multiple approaches for achieving this task.
DirectoryIterator: The Preferred Choice
PHP's DirectoryIterator class offers an optimized solution:
<code class="php">foreach (new DirectoryIterator('.') as $file) { if ($file->isDot()) continue; echo $file->getFilename() . '<br>'; }</code>
Scandir: An Alternative Route
Scandir provides a simpler option:
<code class="php">$files = scandir('.'); foreach ($files as $file) { if ($file == '.' || $file == '..') continue; echo $file . '<br>'; }</code>
Opendir and Readdir: Legacy Option
For legacy code compatibility:
<code class="php">if ($handle = opendir('.')) { while (false !== ($file = readdir($handle))) { if ($file == '.' || $file == '..') continue; echo $file . '<br>'; } closedir($handle); }</code>
Glob: Powerful Pattern Matching
Glob offers a versatile approach with pattern matching:
<code class="php">foreach (glob("*") as $file) { if ($file == '.' || $file == '..') continue; echo $file . '<br>'; }</code>
Note that using "" in glob allows for customizable patterns (e.g., "glob('.txt')" retrieves text files).
The above is the detailed content of How Can I Retrieve Filenames from a Directory in PHP?. For more information, please follow other related articles on the PHP Chinese website!