第26章 PHP 目录遍历与文件高级操作

一、目录基础操作

1. 创建目录

php

// 创建单层目录
mkdir("upload");
// 创建多级目录
mkdir("a/b/c",0777,true);
 

2. 删除目录

php

// 只能删除空目录
rmdir("upload");
 

3. 获取当前目录

php

echo DIR; // 当前文件所在目录
echo getcwd(); // 当前工作目录
 

二、scandir 遍历目录

列出目录下所有文件和子目录

php

$arr = scandir("./");
print_r($arr);
 

说明:会包含  .  和  .. ,需手动过滤。

三、遍历目录并过滤无用项

php

$files = scandir("./");
foreach($files as $v){
if($v == '.' || $v == '..'){
continue;
}
echo $v."";
}
 

四、判断文件与目录类型

php

$path = "test.txt";
if(is_file($path)){
echo "这是文件";
}elseif(is_dir($path)){
echo "这是目录";
}
 

五、获取文件属性

php

// 文件大小 字节
echo filesize("test.txt");
// 文件修改时间
echo date("Y-m-d H:i:s",filemtime("test.txt"));
// 文件是否可读写
is_readable();
is_writable();
 

六、文件重命名与移动

php

// 重命名
rename("old.txt","new.txt");
// 移动文件(本质也是rename)
rename("test.txt","upload/test.txt");
 

七、递归遍历多级目录

php

function scanAll($path){
$files = scandir($path);
foreach($files as $v){
if($v == '.' || $v == '..') continue;
$newPath = $path."/".$v;
echo $newPath."";
// 如果是目录,递归继续遍历
if(is_dir($newPath)){
scanAll($newPath);
}
}
}
scanAll("./");
 

八、删除非空目录(递归删除)

php

function delDir($path){
if(!is_dir($path)) return;
$files = scandir($path);
foreach($files as $v){
if($v=='.'||$v=='..')continue;
$file = $path."/".$v;
// 文件直接删除
is_file($file) ? unlink($file) : delDir($file);
}
// 最后删除空目录
rmdir($path);
}
 

九、本章核心总结

1.  mkdir  第三个参数  true  可创建多级目录
2.  scandir  遍历目录,需过滤  .  和  .. 
3.  rename  既能重命名,也能移动文件
4. 多级目录遍历、删除必须用递归
5. 项目后台文件管理器、缓存清理、批量删除都用本章知识点
【瓜分奖池】PHP基础第二十六章 第5张插图