Home > Backend Development > PHP Problem > How to delete directories recursively in php

How to delete directories recursively in php

藏色散人
Release: 2023-03-03 15:28:01
Original
2691 people have browsed it

php method to recursively delete a directory: first create a PHP sample file; then obtain the path of the file through the "DATA_DIR .'/compiled/';" method; then list the files and directories; and finally delete using the recursive method Directory is enough.

How to delete directories recursively in php

Recommended: "PHP Video Tutorial"

php Recursively delete directories

First of all, you need to know what recursion is, so that it will be easy to read and write recursive code later.

The recursive code listed below is to delete the file directory, and you can make slight changes to display the file. And directory

The code is as follows:

public function clear(){
    $compile  = DATA_DIR .'/compiled/';  //指文件所在路径
    _rmdir($compile,1);
 }
// 列出文件和目录
function _scandir($dir) {
    if(function_exists('scandir')) return scandir($dir);   // 有些服务器禁用了scandir
    $dh = opendir($dir);
    $arr = array();
    while($file = readdir($dh)) {
        if($file == '.' || $file == '..') continue;
        $arr[] = $file;
    }
    closedir($dh);
    return $arr;
}
// 递归删除目录
function _rmdir($dir, $keepdir = 0) {
    if(!is_dir($dir) || $dir == '/' || $dir == '../') return FALSE;    // 避免意外删除整站数据
    $files = _scandir($dir);
    foreach($files as $file) {
        if($file == '.' || $file == '..') continue;
        $filepath = $dir.'/'.$file;
        if(!is_dir($filepath)) {
            try{unlink($filepath);}catch(Exception $e){}
        }else{
            _rmdir($filepath);
        }
    }
    if(!$keepdir) try{rmdir($dir);}catch(Exception $e){}
    return TRUE;
}
Copy after login

The above is the detailed content of How to delete directories recursively in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template