Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better to read files from a directory using PHP - glob() or scandir() or readdir()? [closed]

Tags:

directory

php

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?

like image 275
Alfred Avatar asked Aug 17 '13 15:08

Alfred


1 Answers

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();
   }
}
like image 118
Paweł Zegardło Avatar answered Oct 27 '22 22:10

Paweł Zegardło