php程序开发过程中,需要实现删除指定文件夹和文件夹下的所有文件也是常有的事,如果指定的文件下还有文件夹,文件夹中又包含文件和文件的时候,此时要想实现该功能就要使用递归了。
下面就介绍几个函数:opendir、unlink、is_dir、file_exists、rmdir。
opendir()函数
和closedir函数一起使用,打开一个目录,读取它的内容,然后关闭:
$dir = "/images/";
// 打开目录,然后读取其内容
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "
";
}
closedir($dh);
}
}
?>
unlink()函数
删除文件。若成功,则返回 true,失败则返回 false。
is_dir() 函数
检查指定的文件是否是目录。
file_exists() 函数
检查文件或目录是否存在。如果指定的文件或目录存在则返回 true,否则返回 false。
rmdir() 函数
删除空的目录。若成功,则该函数返回 true。若失败,则返回 false。
以上几个函数可以构成一个删除整个文件夹的函数:
function delDirAndFile($path, $delDir = false)
{
if (is_array($path)) {
foreach ($path as $subPath) {
delDirAndFile($subPath, $delDir);
}
}
if (is_dir($path)) {
$handle = opendir($path);
if ($handle) {
while (false !== ($item = readdir($handle))) {
if ($item != "." && $item != "..") {
is_dir("$path/$item") ? delDirAndFile("$path/$item", $delDir) : unlink("$path/$item");
}
}
closedir($handle);
if ($delDir) {
return rmdir($path);
}
}
} else {
if (file_exists($path)) {
return unlink($path);
} else {
return false;
}
}
}