You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何实现文件夹内容展示、点击文件下载、点击文件夹进入查看功能

实现方案

核心改造逻辑如下:

  • 增加目录参数接收能力,支持切换不同层级的文件夹
  • 区分文件、文件夹类型,分别生成下载、目录跳转逻辑
  • 增加路径安全校验,避免用户通过路径穿越访问Web根目录以外的敏感文件
  • 修正链接路径规则,确保多层级子目录可以正常跳转

完整可运行代码

<?php
// 配置允许访问的根目录,所有开放文件都限制在该目录下
$baseDir = __DIR__ . '/src';
// 接收当前访问的路径参数,默认空值对应src根目录
$currentPath = isset($_GET['path']) ? trim($_GET['path'], '/') : '';
// 拼接真实物理路径
$fullPath = realpath($baseDir . '/' . $currentPath);

// 安全校验:拦截路径穿越的非法请求
if (!$fullPath || strpos($fullPath, realpath($baseDir)) !== 0) {
    die('非法路径访问');
}

// 如果访问对象是文件,直接触发下载
if (is_file($fullPath)) {
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($fullPath) . '"');
    header('Content-Length: ' . filesize($fullPath));
    readfile($fullPath);
    exit;
}

// 如果访问对象是文件夹,遍历目录内所有内容
$filesInFolder = [];
$iterator = new FilesystemIterator($fullPath);
foreach ($iterator as $entry) {
    $filesInFolder[] = [
        'name' => $entry->getFilename(),
        'is_dir' => $entry->isDir(),
        'path' => ltrim($currentPath . '/' . $entry->getFilename(), '/')
    ];
}

// 非根目录下展示返回上一级入口
if ($currentPath !== '') {
    $parentPath = dirname($currentPath);
    echo "<a href='?path=" . urlencode($parentPath == '.' ? '' : $parentPath) . "'> 返回上一级 </a><br>";
}

// 输出目录内容列表
foreach ($filesInFolder as $item) {
    if ($item['is_dir']) {
        // 文件夹跳转对应目录,名称用斜体标识
        echo "<a href='?path=" . urlencode($item['path']) . "'> *" . $item['name'] . "* </a><br>";
    } else {
        // 文件点击触发下载
        echo "<a href='?path=" . urlencode($item['path']) . "'> " . $item['name'] . " </a><br>";
    }
}
?>

部署使用说明

  • 将以上代码保存为index.php,放在项目根目录与src文件夹同级即可运行
  • 所有需要开放访问的文件、文件夹都放入src目录即可自动识别

内容的提问来源于stack exchange,提问作者mitas1c

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 12:15:04