I am a beginner in PHP. I would like to read files from a specific folder / directory. I don't want sub-folders or files in them. I just want to list out direct files inside the directory. I ended up with 3 solutions, glob()
, readdir()
, and scandir()
. I can do file listing like;
foreach (glob("*.*") as $filename) {
echo $filename."<br />";
}
and
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: .".$file."<br />";
}
closedir($dh);
}
}
and
$files = scandir($dir);
foreach($files as $val){
echo $val;
}
Which one is faster and more efficient?
Maybe DirectoryIterator from SPL? http://php.net/manual/en/class.directoryiterator.php
foreach(new DirectoryIterator($dir_path) as $item) {
if (!$item->isDot() && $item->isFile()) {
echo $item->getFilename();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With