4

I'm coding a simple web report system for my company. I wrote a script for index.php that gets a list of files in the "reports" directory and creates a link to that report automatically. It works fine, but my problem here is that readdir( ) keeps returning the . and .. directory pointers in addition to the directory's contents. Is there any way to prevent this OTHER THAN looping through the returned array and stripping them manually?

Here is the relevant code for the curious:

//Open the "reports" directory
$reportDir = opendir('reports');

//Loop through each file
while (false !== ($report = readdir($reportDir)))
{
  //Convert the filename to a proper title format
  $reportTitle = str_replace(array('_', '.php'), array(' ', ''), $report);
  $reportTitle = strtolower($reportTitle);
  $reportTitle = ucwords($reportTitle);

  //Output link
  echo "<a href=\"viewreport.php?" . $report . "\">$reportTitle</a><br />";
}

//Close the directory
closedir($reportDir);
DWilliams
  • 451
  • 8
  • 22

5 Answers5

18

In your above code, you could append as a first line in the while loop:

if ($report == '.' or $report == '..') continue;
Paul Lammertsma
  • 37,593
  • 16
  • 136
  • 187
  • A simple enough solution. I was hoping there was perhaps some parameter option on readdir to avoid this but I guess not. This question got about 5 simultaneous answers with pretty much the same exact solution. Accepting this one because it was first. – DWilliams Oct 06 '09 at 14:22
4
array_diff(scandir($reportDir), array('.', '..'))

or even better:

foreach(glob($dir.'*.php') as $file) {
    # do your thing
}
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
2

No, those files belong to a directory and readdir should thus return them. I’d consider every other behaviour to be broken.

Anyway, just skip them:

while (false !== ($report = readdir($reportDir)))
{
  if (($report == ".") || ($report == ".."))
  {
     continue;
  }
  ...
}
Bombe
  • 81,643
  • 20
  • 123
  • 127
1

I would not know another way, as "." and ".." are proper directories as well. As you're looping anyway to form the proper report URL, you might just put in a little if that ignores . and .. for further processing.

EDIT
Paul Lammertsma was a bit faster than me. That's the solution you want ;-)

Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139
0

I wanted to check for the "." and the ".." directories as well as any files that might not be valid based on what I was storing in the directory so I used:

while (false !== ($report = readdir($reportDir)))
{
    if (strlen($report) < 8) continue;
    // do processing
}
meme
  • 11,861
  • 2
  • 19
  • 20