PHP内置服务器,以任何方式配置它来显示目录文件?

gal*_*kas 7 php

您可能知道,从PHP 5.4开始,内置服务器可用.但是,如果您浏览到没有"索引"文件的目录,而是列出所有可用的文件/目录(例如apache),它将为您提供错误.

据我所知,这是设计而不是某种错误.但也许有人知道是否有办法配置它,列出目录的内容?

Nie*_*sol 10

正如Colin在他的评论中所提到的,集成服务器仅用于调试目的,因此您应该期望它不具备您对完整服务器所期望的所有功能.

但是,构建自己index.php的模拟默认Apache索引很容易:

<?php
$dir = substr(dirname($_SERVER['PHP_SELF']),strlen($_SERVER['DOCUMENT_ROOT']));
echo "<h2>Index of ".$dir.":</h2>";
$g = glob("*");
usort($g,function($a,$b) {
    if(is_dir($a) == is_dir($b))
        return strnatcasecmp($a,$b);
    else
        return is_dir($a) ? -1 : 1;
});
echo implode("<br>",array_map(function($a) {return '<a href="'.$a.'">'.$a.'</a>';},$g));
Run Code Online (Sandbox Code Playgroud)

  • @ Radon8472呃...没有.因为我不负责`http://example.com/index.php/ <script> alert('XSS!'); </ script>` (2认同)

Syc*_*yco 5

老问题,但我觉得这仍然有用。

我对使用集成 Web 服务器不仅用于调试感到内疚,而且还与虚拟机或局域网中的其他电脑共享来自我电脑上随机文件夹的文件。

这么说,这是我的更新脚本(它可以与来自任何文件夹的“php -S localhost:8080 -t .script.php”一起使用):

<style>
  a {
    color: black;
    width: 100%;
    display: flex;
    flex-direction: row;
  }

  a:hover {
    background-color: #77AAFF;
    color: black;
  }

  .linkLeft {
    flex-grow: 0;
  }

  .linkCenter {
    flex-grow: 1;
    margin: -3px 10px 3px;
    border-bottom: 1px dotted black;
  }

  .linkRight {
    flex-grow: 0;
  }
</style>
<?php
$dir = realpath(isset($_GET['dir']) ? $_GET['dir'] : ".");
if (is_dir($dir)) {
  echo "<h2>Index of $dir:</h2>\n";
  $files = array_diff(scandir($dir), array('..', '.'));
  usort($files, function($a, $b) use ($dir) {
    if (is_dir("{$dir}/{$a}") == is_dir("{$dir}/{$b}")) {
      return strnatcasecmp($a, $b);
    } else {
      return is_dir("{$dir}/{$a}") ? -1 : 1;
    }
  });
  echo "<a href='?dir=" . urlencode(realpath("{$dir}/..")) . "'>?</a>\n";
  foreach ($files as $file) {
    if (is_dir("{$dir}/{$file}")) {
      $typef = "[directory]";
    } else {
      $typef = "[" . pathinfo($file, PATHINFO_EXTENSION) . " file]";
    }
    ?>
    <a href='?dir=<?= urlencode("{$dir}/{$file}"); ?>'>
      <div class='linkLeft'><?= $file; ?></div>
      <div class='linkCenter'></div>
      <div class='linkRight'><?= $typef; ?></div>
    </a>
    <?php
  }
} else if (is_file($dir)) {
  header('Content-Description: File Transfer');
  header('Content-Type: application/octet-stream');
  header('Content-Disposition: attachment; filename="' . basename($dir) . '"');
  header('Expires: 0');
  header('Cache-Control: must-revalidate');
  header('Pragma: public');
  header('Content-Length: ' . filesize($dir));
  readfile($dir);
}
Run Code Online (Sandbox Code Playgroud)