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!