使用 php 删除所有文件、文件夹及其子文件夹 [英] Remove all files, folders and their subfolders with php

查看:38
本文介绍了使用 php 删除所有文件、文件夹及其子文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个脚本,它可以删除整个目录及其所有子文件夹、文件等.我尝试使用这个功能,几个月前我在互联网上找到了这个功能,但它不能完全工作.

I need a script which can remove a whole directory with all their subfolders, files and etc. I tried with this function which I found in internet before few months ago but it not work completely.

function deleteFile($dir) {
    if(substr($dir, strlen($dir)-1, 1) != '/') { 
        $dir .= '/'; 
    }
    if($handle = opendir($dir)) { 
        while($obj = readdir($handle)) { 
            if($obj != '.' && $obj != '..') { 
                if(is_dir($dir.$obj)) { 
                    if(!deleteFile($dir.$obj)) {
                        echo $dir.$obj."<br />";
                        return false;
                    }
                }
                elseif(is_file($dir.$obj)) { 
                    if(!unlink($dir.$obj)) {
                        echo $dir.$obj."<br />";
                        return false;
                    }
                }
            }
        }
        closedir($handle); 
        if(!@rmdir($dir)) {
            echo $dir.'<br />';
            return false;
        }
        return true;
    }
    return true;
}

为了测试,我使用了 prestashop 的解压存档,我尝试删除解压存档的文件夹,但它不起作用.

For the test I use a unpacked archive of prestashop and I try to delete the folder where archive is unpacked but it doesn't work.

/home/***/public_html/prestashop/img/p/3/
/home/***/public_html/prestashop/img/p/3
/home/***/public_html/prestashop/img/p
/home/***/public_html/prestashop/img

这些是问题文件夹.我第一次想 - 可能是文件的 chmod 有问题"但是当我测试所有文件的 chmod 权限 755(之后是 777) - 结果是一样的.

These are the problem folders. At the first time I think - "May is a problem with the chmod of the files" but when I test with all files chmod permission 755 (after that with 777) - the result was the same.

推荐答案

<?php
  function rrmdir($dir) {
  if (is_dir($dir)) {
    $objects = scandir($dir);
    foreach ($objects as $object) {
      if ($object != "." && $object != "..") {
        if (filetype($dir."/".$object) == "dir") 
           rrmdir($dir."/".$object); 
        else unlink   ($dir."/".$object);
      }
    }
    reset($objects);
    rmdir($dir);
  }
 }
?>

php.net

对我来说很好

这篇关于使用 php 删除所有文件、文件夹及其子文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆