DWilliams
DWilliams

Reputation: 451

PHP readdir( ) returns " . " and " .. " entries

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);

Upvotes: 4

Views: 8680

Answers (5)

meme
meme

Reputation: 12197

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
}

Upvotes: 0

SilentGhost
SilentGhost

Reputation: 319651

array_diff(scandir($reportDir), array('.', '..'))

or even better:

foreach(glob($dir.'*.php') as $file) {
    # do your thing
}

Upvotes: 4

Bombe
Bombe

Reputation: 83869

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;
  }
  ...
}

Upvotes: 2

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56707

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 ;-)

Upvotes: 1

Paul Lammertsma
Paul Lammertsma

Reputation: 38252

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

if ($report == '.' or $report == '..') continue;

Upvotes: 17

Related Questions