开发者

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


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

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


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

or even better:

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


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


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


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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜