ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## 目录处理 ### 使用 opendir, readdir, closedir *resource opendir ( string $path )* 功能: 打开一个目录句柄。 *string readdir ( resource $dir_handle )* 功能: 返回目录中下一个文件的文件名。 *void closedir ( resource $dir_handle )* 功能: 关闭目录句柄。 ``` <?php function dir_tree($dir) { $output = array(); $handle = opendir($dir); while (false !== ($file = readdir($handle))) { if ($file != '.' && $file != '..') { $path = $dir . '/' . $file; if (is_dir($path)) { $output[$file] = dir_tree($path); } else { $output[] = basename($path); } } } closedir($handle); return $output; } $dir = '/home/koogua/tmp'; $output = dir_tree($dir); print_r($output); ?> ``` ### 使用 dir [Directory](http://php.net/manual/zh/class.directory.php) *dir ( string $directory )* 功能: 以面向对象的方式访问目录。 ``` <?php function dir_tree($dir) { $output = array(); $obj = dir($dir); while (false !== ($file = $obj->read())) { if ($file != '.' && $file != '..') { $path = $dir . '/' . $file; if (is_dir($path)) { $output[$file] = dir_tree($path); } else { $output[] = basename($path); } } } $obj->close(); return $output; } $dir = '/home/koogua/tmp'; $output = dir_tree($dir); print_r($output); ?> ``` ### 使用 scandir *array scandir ( string $directory )* 功能: 列出指定路径中的文件和目录。 ``` <?php function dir_tree($dir) { $output = array(); $files = scandir($dir); foreach ($files as $file) { if ($file != '.' && $file != '..') { $path = $dir . '/' . $file; if (is_dir($path)) { $output[$file] = dir_tree($path); } else { $output[] = basename($path); } } } return $output; } $dir = '/home/koogua/tmp'; $output = dir_tree($dir); print_r($output); ?> ``` ### 使用 mkdir, rmdir *bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = false ]] )* 功能: 尝试新建一个指定的目录。 *bool rmdir ( string $dirname )* 功能: 尝试删除所指定的目录。 该目录必须是空的,而且要有相应的权限。 ``` <?php $path = '/home/koogua/tmp/1984/03/02'; if (!mkdir($path, 0775, true)) { echo 'make dir failed.' . PHP_EOL; } $path = '/home/koogua/tmp/1984/03'; if (!rmdir($path)) { echo 'remove dir failed.' . PHP_EOL; } ?> ```