开发者

Delete folder in php

I am trying to delete a folder using this script :

function Delete($path)
{
    if (is_dir($path) === true)
    {
        $files = array_diff(scandir($path), array('.', '..'));

        foreach ($files as $file)
        {
                Delete(realpath($path) . '/' . $file);
        }

        return rmdir($path);
    }

    else if (is_file($path) === true)
    {
        return unlink($path);
    }

    return false;
}

Delete('tmp');

It works in my Xampp server, but not on my webserver. I have changed the permissions of the folder and of the file it contains to 0777. So it should be writable(or in this case erasable)开发者_开发技巧 but nothing happens. I have even tryied giving the absolute path of the folder as the parameter of the function, but still nothing.Any ideas?


Use this :

function delTree($dir)
{
 $files = glob( $dir . '*', GLOB_MARK );
 foreach( $files as $file 
 {
  if( is_dir( $file ) )
   delTree( $file );
  else
   @unlink( $file );
 }

 if( is_dir($dir) ) rmdir( $dir );
};


Does it return false? Or it returns true but doesn't actually remove?

Normally I'd just guess it's a permissions problem.

Try making a folder with mkdir from PHP so PHP is the owner (so to speak) and try to remove that with your function.

If it works, it's a permissions/owner issue.


You can Try this code

<?php
$files = glob('application/*'); foreach($files as $file){  if(is_file($file)) unlink($file);  }
?>

Or,

   function viewDir($path) {
    return is_file($path) ?
            @unlink($path) :
            array_map(__FUNCTION__, glob($path.'/*')) == @rmdir($path);
}
$dir=$_SERVER["DOCUMENT_ROOT"]."/xxxx/xxxx";
echo $dir;
viewDir($dir);


May be some files are opened using php like fopen and that time it will not delete the folder or directory. I have faced the same issue when I tried to delete a file/folder


Try something like this.

<?php
function delete_directory($target) {
         if (is_dir($target))
           $dir_handle = opendir($target);
     if (!$dir_handle)
          return false;
     while($file = readdir($dir_handle)) {
           if ($file != "." && $file != "..") {
                if (!is_dir($dirname."/".$file))
                     unlink($dirname."/".$file);
                else
                     delete_directory($target.'/'.$file);
           }
     }
     closedir($dir_handle);
     rmdir($target);
     return true;
}

?>

Hope this helps.


Try this line of code to delete a folder or folder files I hope this will help you

function deleteAll($str) {
        if (is_file($str)) {
            return unlink($str);
        }
        elseif (is_dir($str)) {
            $scan = glob(rtrim($str,'/').'/*');
            foreach($scan as $index=>$path) {
                $this->deleteAll($path);
            }            
            return @rmdir($str);
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜