PHP - rmdir (permission denied)

后端 未结 4 1680
挽巷
挽巷 2021-01-13 20:48

I have an easy script to create and delete a folder, but when I try to delete a folder, it brings up and error.

The code:



        
4条回答
  •  梦谈多话
    2021-01-13 21:08

    For the purpose of this answer, I will put the security risks of allowing any and all uploads in a directory aside. I know it's not secure, but I feel this issue is outside the scope of the original question.

    As everybody said, it can be a permission problem. But since you've created the directory in your code (which is most likely running as the same user when deleted). It doubt it is that.

    To delete a directory, you need to make sure that:

    1. You have proper permissions (as everyone pointed out).

    2. All directory handles must be closed prior to deletion.
      (leaving handles open can cause Permission denied errors)

    3. The directory must be empty. rmdir() only deletes the directory, not the files inside. So it can't do its job if there is still stuff inside.

    To fix number 2, it is extremely simple. If you are using something like this:

    $hd = opendir($mydir);
    

    Close your handle prior to deletion:

    closedir($hd);
    

    For number 3, what you want to do is called a recursive delete. You can use the following function to achieve this:

    function force_rmdir($path) {
      if (!file_exists($path)) return false;
    
      if (is_file($path) || is_link($path)) {
        return unlink($path);
      }
    
      if (is_dir($path)) {
        $path = rtrim($path, DIR_SEPARATOR) . DIR_SEPARATOR;
    
        $result = true;
    
        $dir = new DirectoryIterator($path);
    
        foreach ($dir as $file) {
          if (!$file->isDot()) {
            $result &= force_rmdir($path . $file->getFilename(), false, $sizeErased);
          }
        }
    
        $result &= rmdir($path);
        return $result;
      }
    }
    

提交回复
热议问题