Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

php

readdir

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);
like image 541
DWilliams Avatar asked Nov 28 '22 05:11

DWilliams


2 Answers

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

if ($report == '.' or $report == '..') continue;
like image 64
Paul Lammertsma Avatar answered Dec 06 '22 04:12

Paul Lammertsma


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

or even better:

foreach(glob($dir.'*.php') as $file) {
    # do your thing
}
like image 30
SilentGhost Avatar answered Dec 06 '22 06:12

SilentGhost