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:
foreach (new DirectoryIterator('.') as $file) {
if($file->isDot()) continue;
print $file->getFilename() . '
';
}
scandir
This function retrieves an array of files and directories in a directory:
$files = scandir('.');
foreach($files as $file) {
if($file == '.' || $file == '..') continue;
print $file . '
';
}
readdir and opendir
This combination of functions provides access to a directory handle:
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if($file == '.' || $file == '..') continue;
print $file . '
';
}
closedir($handle);
}
glob
This function is useful for matching files based on patterns:
foreach (glob("*") as $file) {
if($file == '.' || $file == '..') continue;
print $file . '
';
}
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_'.
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