How to get the file names inside a directory using PHP?
I couldn't find the relevant command using Google, so I hope that this question will help those who are asking along the similar lines.
How to get the file names inside a directory using PHP?
I couldn't find the relevant command using Google, so I hope that this question will help those who are asking along the similar lines.
The old way would be:
As already mentioned the directory iterator might be the better way for PHP 5.
The Paolo Bergantino's answer was fine but is now outdated!
Please consider the below official ways to get the Files inside a directory.
FilesystemIterator
FilesystemIterator
has many new features compared to its ancestorDirectoryIterator
as for instance the possibility to avoid the statementif($file->isDot()) continue;
. See also the question Difference betweenDirectoryIterator
andFilesystemIterator
.RecursiveDirectoryIterator
This snippet lists PHP files in all sub-directories.
See also the Wrikken's answer.
There's a lot of ways. The older way is
scandir
butDirectoryIterator
is probably the best way.There's also
readdir
(to be used withopendir
) andglob
.Here are some examples on how to use each one to print all the files in the current directory:
DirectoryIterator
usage: (recommended)scandir
usage:opendir
andreaddir
usage:glob
usage:As mentioned in the comments,
glob
is nice because the asterisk I used there can actually be used to do matches on the files, soglob('*.txt')
would get you all the text files in the folder andglob('image_*')
would get you all files that start with image_