Getting the names of all files in a directory with PHP
You need to surround $file = readdir($handle)
with parentheses.
Here you go:
$log_directory = 'your_dir_name_here';
$results_array = array();
if (is_dir($log_directory))
{
if ($handle = opendir($log_directory))
{
//Notice the parentheses I added:
while(($file = readdir($handle)) !== FALSE)
{
$results_array[] = $file;
}
closedir($handle);
}
}
//Output findings
foreach($results_array as $value)
{
echo $value . '<br />';
}
Don't bother with open/readdir and use glob
instead:
foreach(glob($log_directory.'/*.*') as $file) {
...
}
As the accepted answer has two important shortfalls, I'm posting the improved answer for those new comers who are looking for a correct answer:
foreach (array_filter(glob('/Path/To/*'), 'is_file') as $file)
{
// Do something with $file
}
- Filtering the
globe
function results withis_file
is necessary, because it might return some directories as well. - Not all files have a
.
in their names, so*/*
pattern sucks in general.
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.