PHP readdir () returns records "." And ".."
I am coding a simple web reporting system for my company. I wrote a script for index.php that gets a list of files in the "reports" directory and automatically creates a link to that report. It works fine, but my problem here is readdir () keeps returning. and .. directory pointers in addition to directory contents. Is there a way to prevent this OTHER THAN loop through the returned array and delete them manually?
Here's 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 the above code, you can add to the first line in the loop while
:
if ($report == '.' or $report == '..') continue;
array_diff(scandir($reportDir), array('.', '..'))
or even better:
foreach(glob($dir.'*.php') as $file) {
# do your thing
}
No, these files are owned by the directory, but readdir
should return them. Identify every other behavior that needs to be broken.
Anyway, just skip them:
while (false !== ($report = readdir($reportDir)))
{
if (($report == ".") || ($report == ".."))
{
continue;
}
...
}
I don't know any other way like "." and ".." are the proper directories. Since you are looping about generating the correct report url anyway, you can just add a little if
that ignores .
and ..
for further processing.
CHANGE
Gender Lammertsma was a bit faster than me. This is the solution you want; -)
I wanted to check for "." and directories ".." as well as any files that might be invalid based on what I stored in the directory, so I used:
while (false !== ($report = readdir($reportDir)))
{
if (strlen($report) < 8) continue;
// do processing
}