【问题标题】:PHP list file with exceptionPHP列表文件异常
【发布时间】:2017-01-06 01:52:42
【问题描述】:

我制作了一个 PHP 页面,其中显示了一个文件夹中的文件列表。现在我不希望有人直接访问这个文件夹,我计划添加一个重定向到 index.php 的 PHP 脚本。只是我不希望这个文件出现在列表中

我可以只为这个扩展添加例外吗?或者有什么更好的主意?

if ($handle = opendir('manual')) {
    while (false !== ($entry = readdir($handle))) {
           if ($entry != "." && $entry != "..") {
               echo "<a href='manual/$entry' target='_blank'>$entry</><br>";
           }
     }
     closedir($handle);
}

【问题讨论】:

  • 您可以在manual 文件夹中添加.htaccess 规则,这将阻止对该目录的访问——但是您上面代码输出的所有链接都将被破坏。在这种情况下,不要引用'manual/$entry',而是调用另一个文件,如foo.php?file=$entry,foo.php 负责获取$entry 的内容。这整体真的很草率。

标签: php readdir opendir


【解决方案1】:

如果您不希望 index.php 文件显示在此列表中,则只需使用 if 语句即可。

if ($handle = opendir('manual')) {
    while (false !== ($entry = readdir($handle))) {
           if ($entry != "." && $entry != "..") {
               if($entry!='index.php') // Go ahead only if the file is not index.php
                   echo "<a href='manual/$entry' target='_blank'>$entry</a><br>";
           }
     }
     closedir($handle);
}

而且,如果你想隐藏所有的php文件,那么你可以使用preg_match

if ($handle = opendir('manual')) {
    while (false !== ($entry = readdir($handle))) {
           if ($entry != "." && $entry != "..") {
               if (!preg_match('/.php/', $entry)) // Go ahead only if the file is not having .php as it's extension
                   echo "<a href='manual/$entry' target='_blank'>$entry</a><br>";
           }
     }
     closedir($handle);
}

【讨论】:

  • 确定这项工作,但我可以阻止所有 .php 文件出现吗?
  • 您可以使用preg_match(),或查看stackoverflow.com/questions/173868/… 获取扩展名并进行比较。
  • 是的,您可以使用preg_match。我已经相应地编辑了我的答案。
【解决方案2】:

你可以简单地使用一个标志变量来识别访问者的状态,如果没有变量,让他重定向。通常我们使用 session 全局变量来做这项工作

【讨论】:

    猜你喜欢
    • 2017-03-07
    • 2011-06-23
    • 1970-01-01
    • 2014-08-18
    • 1970-01-01
    • 2020-10-15
    • 2018-03-22
    • 1970-01-01
    • 2011-01-11
    相关资源
    最近更新 更多