Home > Article > Backend Development > How to List File Names in a Directory Using PHP?
How to Obtain File Names within a Directory Using PHP
In PHP programming, retrieving the file names present within a directory can be accomplished through various methods. This article showcases several approaches for accessing and displaying the file names in the current directory.
DirectoryIterator (Recommended):
DirectoryIterator is a modernized and preferred method for iterating over directory contents. Its usage is demonstrated below:
<code class="php">foreach (new DirectoryIterator('.') as $file) { if($file->isDot()) continue; print $file->getFilename() . '<br>'; }</code>
scandir:
The scandir function scans the specified directory and returns an array containing the file names. Here's an example:
<code class="php">$files = scandir('.'); foreach($files as $file) { if($file == '.' || $file == '..') continue; print $file . '<br>'; }</code>
opendir and readdir:
This approach involves opening the directory using opendir and then iterating through the files using readdir. Here's how it's done:
<code class="php">if ($handle = opendir('.')) { while (false !== ($file = readdir($handle))) { if($file == '.' || $file == '..') continue; print $file . '<br>'; } closedir($handle); }</code>
glob:
glob is a pattern-matching function that can be used to retrieve files matching a specified pattern. Here's how it can be utilized:
<code class="php">foreach (glob("*") as $file) { if($file == '.' || $file == '..') continue; print $file . '<br>'; }</code>
The glob function allows for more flexibility in specifying file patterns, making it suitable for specific file name matching needs.
The above is the detailed content of How to List File Names in a Directory Using PHP?. For more information, please follow other related articles on the PHP Chinese website!