"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Retrieve Filenames from a Directory in PHP?

How to Retrieve Filenames from a Directory in PHP?

Published on 2024-11-07
Browse:732

How to Retrieve Filenames from a Directory in PHP?

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_'.

Release Statement This article is reprinted at: 1729248137 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

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