PHP 查看文件夹内容

PHP viewing folder content

我正在尝试创建一个文件服务器。

我想做的是 -> 在页面上会显示很多文件夹,当你点击一个时,你会看到它的内容,如果这个文件夹里面有一个文件夹,你可以点击它将显示该文件夹的内容。

这是我目前拥有的代码,但是我不知道如何继续,因为我对 PHP 还很陌生。

function searchFolders($dir){
        $filesInFolder = array();
        $iterator = new FilesystemIterator($dir);

        foreach($iterator as $file){
            if(is_dir($file)){
                echo "<h1>Folder</h1>";
                searchFolders($file);
            }else{
                $filesInFolder[] = $file;
            }
        }

        foreach($filesInFolder as $file){
            echo "<a href='/$file'> $file </a><br>";
        }
    }
searchFolders('src')

以下内容我相信会对您有所帮助。我使用 PHP 的 FilesystemIterator, Bootstrap 创建了一个目录和文件列表界面。写给 PHP 8.

下面是使用中的代码:

此示例使用两个文件,Reader.phpindex.php...

Reader.php

<?php

class Reader {

    public function __construct(
        public string $root
    ) {}

    /**
     * Remove the root directory from the path value.
     *
     * @param string $path
     * @return string
     */
    public function removeRootFromPath(string $path) {
        $path = preg_replace('/^' . preg_quote($this->root, '/') . '/', '', $path);
        $path = $this->cleanPath($path);
        return DIRECTORY_SEPARATOR . ltrim($path, DIRECTORY_SEPARATOR);
    }

    /**
     * Add the root directory to the path value.
     *
     * @param string $path
     * @return string
     */
    public function addRootToPath(string $path) {
        $path = $this->removeRootFromPath($path);
        $path = ltrim($path, DIRECTORY_SEPARATOR);
        $root = rtrim($this->root, DIRECTORY_SEPARATOR);
        return $root . DIRECTORY_SEPARATOR . $path;
    }

    /**
     * Replace dot notation in paths i.e ../ and ./
     *
     * @param string $dir
     * @return string
     */
    public function cleanPath(string $dir) {
        $sep = preg_quote(DIRECTORY_SEPARATOR, '/');
        return preg_replace('/\.\.' . $sep . '|\.' . $sep . '/', '', $dir);
    }

    /**
     * @param string $dir
     * @return FilesystemIterator|null
     */
    public function readDirectory(string $dir) {
        $dir = $this->addRootToPath($dir);

        try {
            return new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
        } catch (UnexpectedValueException $exception) {
            return null;
        }
    }

}

index.php

<?php
require_once 'Reader.php';

$root_dir = 'src'; // Relative to current file. Change to your path!
$reader = new Reader(__DIR__ . DIRECTORY_SEPARATOR . $root_dir);
$target = $reader->removeRootFromPath(!empty($_GET['path']) ? $_GET['path'] : '/');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Directory viewer</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

    <div class="container my-5">

        <h1>Current: <?= $target; ?></h1>

        <table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th class="w-25">
                        Type
                    </th>
                    <th class="w-75">
                        File
                    </th>
                </tr>
            </thead>
            <tbody>
                <?php if ($target !== $reader->removeRootFromPath('/')): ?>
                    <tr>
                        <td>
                            Parent
                        </td>
                        <td>
                            <a href="?path=<?= urlencode($reader->removeRootFromPath(dirname($target))); ?>">../</a>
                        </td>
                    </tr>
                <?php endif ?>
                <?php if ($results = $reader->readDirectory($target)): ?>
                    <?php foreach($results as $result): ?>
                        <?php
                        // Make the full path user friendly by removing the root directory.
                        $user_friendly = $reader->removeRootFromPath($result->getFileInfo());

                        $type = $result->getType();
                        ?>
                        <tr>
                            <td>
                                <?= ucfirst($type); ?>
                            </td>
                            <td>
                                <?php if ($type === 'dir'): ?>
                                    <a href="?path=<?= urlencode($user_friendly); ?>"><?= $user_friendly; ?></a>
                                <?php else: ?>
                                    <!-- Maybe add a download link to the file -->
                                    <?= $user_friendly; ?>
                                <?php endif ?>
                            </td>
                        </tr>
                    <?php endforeach ?>
                <?php else: ?>
                    <tr>
                        <td colspan="2">
                            Directory does not exist.
                        </td>
                    </tr>
                <?php endif ?>
            </tbody>
        </table>
    </div>

</body>
</html>

Reader class 包括许多辅助方法 removeRootFromPath()addRootToPath()cleanPath() 这些方法的组合有助于防止用户访问源目录之外的路径。

例如,如果您的文件系统类似于...

/var/www/Reader.php
/var/www/index.php
/var/www/src/

你列出了 /var/www/src/ 目录,没有路径清理方法,用户可以将输入修改为 ../../ 并最终到达你的文件系统根目录,这是你没有的想要!

这是我为了这个问题而快速整理的东西,应该用作指南。