删除包含图像的相册文件夹

时间:2012-09-07 12:51:04

标签: php image directory sql-delete

我试图删除包含所有图片的相册。存储的相册和图像的路径是 ../_ uploads /< album_name> /< image_file> 。这是我的delete_album.php中的代码:

    if(isset($_GET['album_id']) === true){
    $album_id = (int)$_GET['album_id'];
    $query_album_info = "SELECT `albums`.`album_id`, `albums`.`album_name`, `images`.`image_name`, `images`.`image_ext`
                        FROM `albums`
                        LEFT JOIN `images` ON `albums`.`album_id` = `images`.`album_id`
                        WHERE `albums`.`album_id` = {$album_id}
                        LIMIT 1 ";
    $album_info = mysql_query($query_album_info, $connection) or die(mysql_error());
    $row_album = mysql_fetch_assoc($album_info);

    $album = $row_album['album_name'];
    $img_file = $row_album['image_name'] . '.' . $row_album['image_ext'];

    $images = scandir("../_uploads/{$album}/");
    unset($images[0]);
    unset($images[1]);
    //echo "<pre>",print_r($images,true),"</pre>";

    foreach($images as $image){
        unlink("../_uploads/{$album}/{$image_file}");
    }
    if(rmdir("../_uploads/{$album}") === true){
        //delete all images of album from database
        $query_delete_images = "DELETE FROM `images` WHERE `album_id` = {$album_id}";
        $delete_images = mysql_query($query_delete_images) or die(mysql_error());
        if(mysql_affected_rows() == 1){         
        }else{
            redirect_to("albums.php?del_imgs=1");
        }
        //delete album from database
        $query_delete_album= "DELETE FROM `albums` WHERE `album_id` = {$album_id}";
        $delete_album= mysql_query($query_delete_album) or die(mysql_error());
        if(mysql_affected_rows() == 1){ 
            redirect_to("albums.php?delete_album=1");
        }else{
            redirect_to("albums.php?delete_error_album=1");
        }
    }else{
        redirect_to("albums.php?rmdir_error=1");
    }

}else{
    redirect_to("albums.php");
}

我从重定向到albums.php得到的错误信息是[i] rmdir_error = 1 [/ i],因此没有图像从数据库和文件夹以及相册中删除,所以rmdir函数没有& #39;工作原因图像仍然存在。有什么想法可能是错的吗?

1 个答案:

答案 0 :(得分:1)

您在循环中使用了错误的变量($image_file而不是$image)。所以没有任何内容被删除,当你试图调用rmdir()时,目录不是空的。

// Use the correct variable in the loop statement: changed $image to $image_file
foreach($images as $image_file) {
    // Don't attempt to remove the current directory or parent
    // Since scandir() will return those too...
    if ($image_file !== "." && $image_file !== "..") {
      unlink("../_uploads/{$album}/{$image_file}");
    }
}