Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the names of all files in a directory with PHP

For some reason, I keep getting a '1' for the file names with this code:

if (is_dir($log_directory)) {     if ($handle = opendir($log_directory))     {         while($file = readdir($handle) !== FALSE)         {             $results_array[] = $file;         }         closedir($handle);     } } 

When I echo each element in $results_array, I get a bunch of '1's, not the name of the file. How do I get the name of the files?

like image 662
DexterW Avatar asked May 27 '10 16:05

DexterW


People also ask

How can I get all filenames in a directory in PHP?

Approach: In order to get all the files from the particular directory, we need to specify the complete path of the file & store the path value in the variable as $mydir. Then use the scandir() function that will scan for the files in a current or specific directory & return an array of files and directories.

How can I get a list of all the subfolders and files present in a directory using PHP?

PHP using scandir() to find folders in a directory The scandir function is an inbuilt function that returns an array of files and directories of a specific directory. It lists the files and directories present inside the path specified by the user.


2 Answers

Don't bother with open/readdir and use glob instead:

foreach(glob($log_directory.'/*.*') as $file) {     ... } 
like image 58
Tatu Ulmanen Avatar answered Sep 28 '22 02:09

Tatu Ulmanen


SPL style:

foreach (new DirectoryIterator(__DIR__) as $file) {   if ($file->isFile()) {       print $file->getFilename() . "\n";   } } 

Check DirectoryIterator and SplFileInfo classes for the list of available methods that you can use.

like image 28
Ilija Avatar answered Sep 28 '22 02:09

Ilija