ChatGPT解决这个技术问题 Extra ChatGPT

List all files in one directory PHP [duplicate]

This question already has answers here: Getting the names of all files in a directory with PHP (15 answers) PHP list all files in directory [duplicate] (5 answers) Closed 9 years ago.

What would be the best way to list all the files in one directory with PHP? Is there a $_SERVER function to do this? I would like to list all the files in the usernames/ directory and loop over that result with a link, so that I can just click the hyperlink of the filename to get there. Thanks!

glob() or scandir() are obvious choices
could you give an example of a code that uses those functions, or explain more about them?
For examples and explanations - the documentation is really the best place to go... It's the official source...
Thats funny that the Stack Overflow "Do your homework" search didn't pick those documents up. Thanks!
$temp_files = glob(__dir__.'/*'); foreach($temp_files as $file) {.............}

M
Mukesh Chapagain

You are looking for the command scandir.

$path    = '/tmp';
$files = scandir($path);

Following code will remove . and .. from the returned array from scandir:

$files = array_diff(scandir($path), array('.', '..'));

This is the more elegant solution. I would also add/recommend $files = array_diff(scandir($path), array('..', '.'));
Actually not $files but $filesAndDirs
$files = array_values(array_diff(scandir($path), array('.', '..'))); // this will reindex
I experienced a small snag finding the directory. $files = array_diff(scandir(__DIR__ .$path), array('.', '..')); solved the problem. From stackoverflow.com/questions/11885717/…
Use array_values() to reindex the array after array_diff() array_values(array_diff(scandir($path), array('..', '.')));
O
Orel Biton

Check this out : readdir()

This bit of code should list all entries in a certain directory:

if ($handle = opendir('.')) {

    while (false !== ($entry = readdir($handle))) {

        if ($entry != "." && $entry != "..") {

            echo "$entry\n";
        }
    }

    closedir($handle);
}

Edit: miah's solution is much more elegant than mine, you should use his solution instead.


this works perfect too $files = scandir($imgspath); $total = count($files); $images = array(); for($x = 0; $x <= $total; $x++): if ($files[$x] != '.' && $files[$x] != '..') { $images[] = $files[$x]; } endfor;
This might be a better solution when performance matter: readdir-vs-scandir.
your advantage is: you can filter in one single loop. Say you only want to have .html files and no files containing 404, you can do this on one loop with your solution. Miah you have to loop over the results again