Delete images from folder using php

I try to delete multiple images from folder and also from database, deleting from database is working fine, problem is with deleting from folder I’m using explode function because I have store multiple images inside one column in database. It just won’t delete images from folder.

    $query = "DELETE FROM table_gallery WHERE id = $deleteId";
    $result = mysqli_query($con, $query);

    while($row = mysqli_fetch_assoc($result)) {
            $temp = explode(',',$row['images'] );
            foreach($temp as $image){
                    $images[]="uploads/gallery/".trim( str_replace( array('[',']') ,"" ,$image ) );
            }
            foreach($images as $file) {
                    // Delete given images
                    unlink($images);
                }
        }

Answer

You have a few issues going on here,

1) Variable Confusion

The most notable is this:

   foreach($images as $file) {
          // Delete given images
          unlink($images);
   }

You are opening the array of $images and then dealing with each element in the array as a string reference ($file), but your unlink() command is calling the array, and you can’t do that.

Unlink requires you to give it a filepath string. Not an array.

Fix:

foreach($images as $file) {
          // Delete given images
          unlink($file);
   }

Better:

As an aside, if unlink($file); does not work, then you should check your filepath is correct. Remember the current PHP working directory is the directory the PHP script is in, so you should probably set your deleted image path to being the full server filepath such as:

 unlink($_SERVER['DOCUMENT_ROOT']. $file); 

To ensure you’re certain of the file you’re deleting.

foreach($images as $file) {
          // Delete given images
          // /serverfolder/accountfolder/public_html/uploads/gallery/imagename.jpg
          unlink($_SERVER['DOCUMENT_ROOT'].$file);
   }

2) Your Safety and Security:

Your variable $deleteId might be safe, but it might not. We can’t tell from the code you show but you should be aware that if the $deleteId variable is, for example;

 $deleteId = '1 OR id > 1';
 // which generates:
 $query = "DELETE FROM table_gallery WHERE id = 1 OR id > 1";

This is a security risk for your SQL and will delete all records on your database table (and folder). You should use Prepared Statements to ensure this doesn’t ever happen.

3) Logic Confusion

you have a reference call mysqli_fetch_assoc but the DELETE SQL command will not return a result set, instead if it is successful it will simply return true.

Returns false on failure. For successful queries which produce a result set, such as SELECT, SHOW, DESCRIBE or EXPLAIN, mysqli_query() will return a mysqli_result object. For other successful queries, mysqli_query() will return true.

You need to structure your code somewhat differently, loading the images column value BEFORE you delete the row.

So, to restructure your code:

    1. Check variables are safe.
    1. load images column values
    1. cycle through values and delete
    1. Once deletion is confirmed then DELETE SQL.

For example:

$query = "SELECT images FROM table_gallery WHERE id = ".(int)$deleteId;
$result = mysqli_query($con, $query);
$abort = false;

while($row = mysqli_fetch_assoc($result)) {
        $temp = explode(',',$row['images'] );
        foreach($temp as $image){
                $images[]="uploads/gallery/".trim( str_replace( array('[',']') ,"" ,$image ) );
        }
        foreach($images as $file) {
                // Delete given images
                if(!unlink($_SERVER['DOCUMENT_ROOT'].$file)){
                   // Delete failed so abort
                   $abort = true; 
                }
            }
       //
       if(!$abort){
           // all correct images on disk deleted ok so delete DB row
           if(mysqli_query($con, "DELETE FROM table_gallery WHERE id = ".(int)$deleteId)){
               // Yay deleted ok!
           }
       }
    }

Closing thought:

You need to learn to read your PHP error logs which will spell out all the above.

Leave a Reply

Your email address will not be published. Required fields are marked *