rmdir()不删除空文件夹 - PHP

时间:2011-10-04 02:16:51

标签: php

我目前正在为朋友的艺术家网页构建一个非常低级别的CMS,这将允许她上传,编辑和删除图像,同时为他们指定类别并发布有关节目的新闻帖子等。

我确信我的这个问题有一个非常简单的解决办法,但我对编程缺乏经验让我感到茫然;所以这里。

问题

问题出现在用户可以删除已上传图像的页面上。以下是出现问题的代码片段:

    // Assign selection to variables in memory...
    $img_id = $data["img_name"];

    // First, collect the file path to the image being deleted...
    $rs = mysql_query("SELECT img_path FROM img_uploads WHERE img_id = '$img_id'") or die(mysql_error());
    list($img_path) = mysql_fetch_row($rs);

    // Then delete that row from the DB...
    mysql_query("DELETE FROM img_uploads WHERE img_id = '$img_id'") or die(mysql_error());

    // Now, using the file path collected earlier, delete that file from the server.
    unlink($img_path);

    // Quickly make sure that the file has been deleted by checking if it exists... if it still exists return error.
    if(file_exists($filename)) {
        $err[] = "ERROR - There was an error deleting the file! Please try again.";
        $_SESSION["errors"] = $err;
        header("Location: img_del.php?doDel=failed");
        exit();
    }

    // Scan the directory now that a file has been deleted to see if the dir is empty. If so, delete it. (No use in having empty folders!)
    $file_types = array("gif","jpg","png"); // file types to scan for...
    $path_parts = pathinfo($img_path); // get the directory from the file path...
    $dir = $path_parts["dirname"] . "/"; // assign it to a new variable...
    $handle = opendir($dir);
    $scan = scandir($dir); // now, scan that directory...
    $image_found = FALSE;
    for($i=0; $i<count($scan); $i++) { 
        if ($scan[$i] != '.' && $scan[$i] != '..' && in_array(end(explode('.', $scan[$i])), $file_types)) { 
            $image_found = TRUE;
        }
    }
    closedir($handle);
    if(!$image_found) {
        rmdir($dir);
    }

我首先删除包含图像信息的数据库行,然后从服务器中删除该文件。 这样可以正常,但是,我还想检查删除该文件后该目录是否为空。我使用循环检查目录是否为空,如果没有找到文件,我运行mkdir()出于某种原因,它一直返回错误,指出该目录不为空

我在网站和网站上搜索了一个解决方案,但我还没找到。我确定它在那里,但我很难找到它为什么我来到这里。我该怎么办?

提前感谢您提交的任何帮助!

注意 我还检查了隐藏的文件和文件夹,但没有运气......

Here is a link to an image that pretty much sums up my problem in a nutshell

1 个答案:

答案 0 :(得分:2)

您确定PHP有权删除该文件吗?既然你说你已经检查过隐藏文件,这似乎是唯一剩下的选择。 CHMOD 0777如果有疑问(我通常不推荐这个,但如果你还是要删除它......),并确保文件夹中有正确的所有者让php删除它。