使用递归函数读取目录结构,结合 mkdir、rmdir、file_put_contents 和 unlink 实现文件增删改查。

目录递归读取与树形展示
通过 scandir() 配合递归函数遍历子目录,构建包含路径、类型和名称的数组结构。

递归函数需要处理当前目录下的所有条目。对于普通文件,直接加入列表;对于子目录,则调用自身再次扫描,并将结果合并到当前层级中。这种方式能生成完整的目录树数据,便于前端渲染为可展开的节点。
核心文件操作接口封装
将文件系统的常用操作封装为独立的函数,确保输入参数安全并处理异常返回。

<?php
class FileManager {
private $basePath;
public function __construct($path) {
$this->basePath = rtrim($path, '/') . '/';
}
// 递归读取目录结构
public function getDirectoryTree($dir = null) {
$currentPath = $dir ?? $this->basePath;
if (!is_dir($currentPath)) return [];
$items = scandir($currentPath);
$tree = [];
foreach ($items as $item) {
if ($item === '.' || $item === '..') continue;
$fullPath = $currentPath . $item;
$node = [
'name' => $item,
'path' => $fullPath,
'type' => is_dir($fullPath) ? 'dir' : 'file'
];
if ($node['type'] === 'dir') {
$node['children'] = $this->getDirectoryTree($fullPath);
}
$tree[] = $node;
}
return $tree;
}
// 创建文件或目录
public function create($target, $content = '', $isDir = false) {
if ($isDir) {
return mkdir($target, 0755, true);
}
return file_put_contents($target, $content) !== false;
}
// 删除文件或目录
public function delete($target) {
if (is_dir($target)) {
$items = scandir($target);
foreach ($items as $item) {
if ($item === '.' || $item === '..') continue;
$this->delete($target . '/' . $item);
}
return rmdir($target);
} else {
return unlink($target);
}
}
}
// 示例用法
$fm = new FileManager('/tmp/test_dir');
echo json_encode($fm->getDirectoryTree(), JSON_PRETTY_PRINT);
程序输出为 JSON 格式的目录树结构。输入变化如修改 $basePath 可切换不同根目录。排错时若发现删除失败,检查递归顺序是否先子后父。
在实现具体功能前,需定义统一的错误处理机制。例如,创建目录时若已存在则忽略,删除文件时需确认权限。这些基础操作的稳定性直接决定管理器的可用性。
批量删除时的路径冲突排查
当同时删除父目录与子文件时,需先执行子项清理再移除父目录,避免 Directory not empty 报错。
该问题源于文件系统对非空目录删除的限制。在递归删除逻辑中,必须保证深度优先的顺序:先处理叶子节点(文件或空目录),再回溯处理父节点。代码中的排序或递归顺序调整即可解决此冲突。