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:
foreach (new DirectoryIterator('.') as $file) {
if($file->isDot()) continue;
print $file->getFilename() . '
';
}
scandir:
The scandir function scans the specified directory and returns an array containing the file names. Here's an example:
$files = scandir('.');
foreach($files as $file) {
if($file == '.' || $file == '..') continue;
print $file . '
';
}
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:
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if($file == '.' || $file == '..') continue;
print $file . '
';
}
closedir($handle);
}
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:
foreach (glob("*") as $file) {
if($file == '.' || $file == '..') continue;
print $file . '
';
}
The glob function allows for more flexibility in specifying file patterns, making it suitable for specific file name matching needs.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3