What is the best way to read files from a directory using PHP - glob () or scandir () or readdir ()?

I am new to PHP. I would like to read files from a specific folder / directory. I do not want to add subfolders or files to them. I just want to specify direct files inside the directory. I ended up with 3 solutions, glob() , readdir() and scandir() . I can make a list of files, for example:

 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 can be faster and more efficient?

Thanks in advance ... :)

+4
source share
1 answer

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(); } } 
+8
source

Source: https://habr.com/ru/post/1497589/


All Articles