tags:

views:

226

answers:

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);
+3  A: 
array_diff(scandir($reportDir), array('.', '..'))

or even better:

foreach(glob($dir.'*.php') as $file) {
    # do your thing
}
SilentGhost
+7  A: 

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

if ($report == '.' or $report == '..') continue;
Paul Lammertsma
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
nice and clean example +1
Andi
A: 

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
A: 

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