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?
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.
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.
Don't bother with open/readdir and use glob
instead:
foreach(glob($log_directory.'/*.*') as $file) { ... }
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.
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