如何用PHP列出D盘文件目录并实现点击下载文件功能
修改方案与代码实现
以下是满足需求的PHP代码,支持访问D盘指定文件夹、区分文件/文件夹操作:
<?php // 配置D盘目标根路径(注意Windows路径用/或\\,推荐用/避免转义) $rootPath = 'D:/文件夹/PDF文件/'; // 获取当前访问的子路径,默认加载根目录 $currentPath = isset($_GET['path']) ? realpath($rootPath . $_GET['path']) : $rootPath; // 安全校验:防止非法目录遍历,确保访问路径始终在根目录范围内 if ($currentPath === false || strpos($currentPath, $rootPath) !== 0) { die('非法访问路径'); } // 处理文件下载请求 if (isset($_GET['download'])) { $fileFullPath = realpath($currentPath . '/' . $_GET['download']); // 验证文件合法性:存在、是文件、且在根目录范围内 if ($fileFullPath && is_file($fileFullPath) && strpos($fileFullPath, $rootPath) === 0) { // 发送下载HTTP头,强制浏览器触发下载而非打开文件 header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . basename($fileFullPath) . '"'); header('Content-Length: ' . filesize($fileFullPath)); // 输出文件内容 readfile($fileFullPath); exit; } else { die('无效的下载文件'); } } // 扫描当前路径下的文件和文件夹,过滤掉.和.. $items = scandir($currentPath); $items = array_diff($items, array('.', '..')); // 遍历输出所有项目 foreach ($items as $item) { $itemFullPath = $currentPath . '/' . $item; $relativePath = str_replace($rootPath, '', $currentPath); if (is_dir($itemFullPath)) { // 文件夹:点击进入子目录,无下载操作 $dirLink = '?path=' . urlencode($relativePath . '/' . $item); echo "<a href='$dirLink'>📂 $item</a><br>"; } else { // 文件:点击触发下载 $fileLink = '?path=' . urlencode($relativePath) . '&download=' . urlencode($item); echo "<a href='$fileLink'>📄 $item</a><br>"; } } ?>
关键说明
路径安全控制
- 用
realpath()处理路径,配合根目录校验,防止恶意目录遍历攻击 - 确保所有访问的路径都被限制在你指定的D盘文件夹内
- 用
文件/文件夹区分处理
- 通过
is_dir()判断项目类型 - 文件夹生成进入子目录的链接,点击后加载对应子目录内容
- 文件生成下载链接,触发PHP的下载逻辑,强制浏览器下载而非直接打开PDF
- 通过
下载功能实现
- 发送
Content-Disposition: attachment头,强制浏览器弹出下载对话框 - 用
readfile()高效输出文件内容,避免内存溢出
- 发送
注意事项
- 确保PHP运行用户(如Apache/IIS的服务用户)拥有D盘目标文件夹的读取权限
- 若PHP配置了
open_basedir限制,需要在php.ini中添加D盘目标路径到允许列表
内容的提问来源于stack exchange,提问作者Chirateep Chatchonbut
相关产品推荐
相关产品推荐

