Home  >  Article  >  PHP Framework  >  thinkphp how to delete a folder

thinkphp how to delete a folder

王林
王林forward
2023-05-29 08:22:281519browse

1. Delete empty folders

To delete an empty folder, we can use PHP’s built-in rmdir() function, it can directly delete an empty folder. In ThinkPHP, we only need to use the path parameter of the rmdir() function to delete the specified folder. For example:

$path = './test'; //要删除的文件夹路径
if(is_dir($path)){
    rmdir($path);
}

In the above example, first we define the path of the folder to be deleted, and then use the is_dir() function to determine whether the path is a directory. If it is a directory, execute it rmdir() function to delete it. It should be noted that this method can only delete empty folders. If there are files or subfolders in the folder, they cannot be deleted.

2. Delete non-empty folders

If you want to delete non-empty folders, we can use the delDir() function to achieve this, as follows It is a simple implementation:

function delDir($path){
    if(is_dir($path)){
        if ($dh = opendir($path)){
            while (($file = readdir($dh)) !== false){
                if ($file != '.' && $file != '..'){
                    $fullpath = $path.'/'.$file;
                    if(!is_dir($fullpath)){
                        unlink($fullpath);
                    }else{
                        delDir($fullpath);
                    }
                }
            }
            closedir($dh);
            rmdir($path);
        }
    }
}

delDir()The function is to delete the directory. It calls itself recursively, first deletes all files in the directory, and then deletes the directory. The specific implementation method is to first use the opendir() function to open the specified directory, and then use the readdir() function to read all files and folders in the directory to determine whether they are . and .., if not handled in the same way.

If it is a file, use the unlink() function to delete it directly; if it is a folder, call the delDir() function recursively to delete the folder and its contents. Finally, use the rmdir() function to delete the empty directory.

The above is the detailed content of thinkphp how to delete a folder. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete