Home > php教程 > php手册 > body text

php 删除非空目录自定义函数

WBOY
Release: 2016-06-13 10:02:15
Original
864 people have browsed it

在php中删除目录如果是空目录我们可直接使用rmdir来删除,但是要删除非空目录我们需要先删除最子级目录的文件然后再删除空目录,其实就是递归删除目录了。

//循环删除目录和文件函数

 代码如下 复制代码

function delDirAndFile( $dirName )
{
if ( $handle = opendir( “$dirName” ) ) {
while ( false !== ( $item = readdir( $handle ) ) ) {
if ( $item != “.” && $item != “..” ) {
if ( is_dir( “$dirName/$item” ) ) {
delDirAndFile( “$dirName/$item” );
} else {
if( unlink( “$dirName/$item” ) )echo “成功删除文件: $dirName/$item
n”;
}
}
}
closedir( $handle );
if( rmdir( $dirName ) )echo “成功删除目录: $dirName
n”;
}
}
?>

//循环目录下的所有文件

 代码如下 复制代码

function delFileUnderDir( $dirName=”../Smarty/templates/templates_c” )
{
if ( $handle = opendir( “$dirName” ) ) {
while ( false !== ( $item = readdir( $handle ) ) ) {
if ( $item != “.” && $item != “..” ) {
if ( is_dir( “$dirName/$item” ) ) {
delFileUnderDir( “$dirName/$item” );
} else {
if( unlink( “$dirName/$item” ) )echo “成功删除文件: $dirName/$item
n”;
}
}
}
closedir( $handle );
}
}

?>

目录删除函数

 代码如下 复制代码

function my_del_dir($directory) 


    { 
        if (is_dir($directory) == false) 
        { 
            exit("The Directory Is Not Exist!"); 
        } 
        $handle = opendir($directory); 
        while (($file = readdir($handle)) !== false) 
        { 
            if ($file != "." && $file != "..") 
            { 
                is_dir("$directory/$file")? 
                my_del_dir("$directory/$file"): 
                unlink("$directory/$file"); 
            } 
        } 
        if (readdir($handle) == false) 
        { 
            closedir($handle); 
            rmdir($directory); 
        } 
    } 
    ?> 

自己写的一个


$sourceDir 要删除的目录路径

调用方法 DeleteDir(“images/abc”);  //删除abc目录

 代码如下 复制代码

function DeleteDir($sourceDir){
$succeed = true;
if(file_exists($sourceDir)){
$objDir = opendir($sourceDir);
while(false !== ($fileName = readdir($objDir))){
if(($fileName != “.”) && ($fileName != “..”)){
chmod(“$sourceDir/$fileName”,0777);
if(!is_dir(“$sourceDir/$fileName”)){
if(!unlink(“$sourceDir/$fileName”)){
$succeed = false;
break;
}
}
else{
DeleteDir(“$sourceDir/$fileName”);
}
}
}
if(!readdir($objDir)){
closedir($objDir);
if(!rmdir($sourceDir)){
$succeed = false;
}
}
}
return $succeed;
}

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template