Delete files then directory

。_饼干妹妹 提交于 2019-12-06 08:03:01

You need to pull the rmdir out of the loop. Something like:

$numfailed = 0;

foreach($files as $file)
{
    $delete = unlink($file);

    if($delete)
    {
        echo $file . " deleted!<br />";
    }
    else
    {
        echo $file . " could not be deleted...<br />";
        $numfailed++;
    }   
}

if($numfailed == 0)
{   
    if(is_dir($path))
    {
        $remove = rmdir($path);

        if($remove)
        {
            echo "directory was deleted</br />";
        }
        else
        {
            echo "directory could not be deleted</br />";
        }
    }
    else
    {
        echo "not a valid directory<br />";
    }
}
else
{
    echo "there are still files in the folder, failed to remove $numfailed";
}

You're trying to remove your directory in the foreach-loop which will delete the files inside that directory.

I'd try deleting all files first and then delete the directory, otherwise it won't be empty and can't be deleted.

Also you $i-counter won't do the job of telling you when the directory is empty: imagine your first file will be deleted, then $i = -1. If now your second file is not deleted, your $i = 0 ... which is the condition to delete the directory, even though it's not empty because at least your second file remains.

rmdir removes a directory, but only if it is empty. You have to delete each file (and each subdirectory with their files) before a directory can be removed.

RobertPitt

Possibly permissions.

As you only deleting certain certain filetypes there may be other files left in the directory that you do not have permissions to delete, there for you cannot delete the folder.

Try checking if the folder is empty before trying to rmdir command on it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!