PHP readdir() 返回“” 。 ”和” ..”条目
我正在为我的公司编写一个简单的网络报告系统。我为index.php 编写了一个脚本,它获取“reports”目录中的文件列表并自动创建该报告的链接。它工作正常,但我的问题是 readdir() 不断返回 .和 .. 除了目录内容之外的目录指针。除了循环返回的数组并手动剥离它们之外,还有什么方法可以防止这种情况发生?
这是好奇者的相关代码:
//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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在上面的代码中,您可以将其作为第一行附加到
while
循环中:In your above code, you could append as a first line in the
while
loop:甚至更好:
or even better:
不,这些文件属于一个目录,因此 readdir 应该返回它们。我认为所有其他行为都被打破了。
无论如何,跳过它们:
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:
我不知道另一种方式,如“。”和“..”也是正确的目录。当您无论如何都要循环形成正确的报告 URL 时,您可能只需放入一些
if
来忽略.
和..
以获得进一步的结果加工。编辑
保罗·拉默茨玛(Paul Lammertsma)比我快一点。这就是您想要的解决方案;-)
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: