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!
$temp_files = glob(__dir__.'/*'); foreach($temp_files as $file) {.............}
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('.', '..'));
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.
$files = scandir($imgspath); $total = count($files); $images = array(); for($x = 0; $x <= $total; $x++): if ($files[$x] != '.' && $files[$x] != '..') { $images[] = $files[$x]; } endfor;
glob()
better! php.net/manual/en/function.glob.php
.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
Success story sharing
$files
but$filesAndDirs
$files = array_diff(scandir(__DIR__ .$path), array('.', '..'));
solved the problem. From stackoverflow.com/questions/11885717/…array_values(array_diff(scandir($path), array('..', '.')));