How to delete multible images in a directory with a checkbox.
-
Continuing from "How to copy files from one directory and adding two supporting files into the copied directory/directories"
We now have moved the necessary files to manage those images in the newly moved directory entitled "archive".
There is one exception, the code below will only delete one image at a time even though multiple checkboxes can be marked for deletion. How would we modify this code (manage.php) to delete all the images that have checkboxes selected?<form action="remove.php" method="POST" > <input type="submit" name="remove" value="Select image and Delete"> <ul> <?php //define location of photo image $photosDir = './images'; //define which file extention are images $photosExt = array('gif','jpg','jpeg','tif','tiff','bmp','png'); //initialize array to hold filenames of images found $photoList = array(); //read directory contents //build photo list if (file_exists($photosDir)) { $dp = opendir($photosDir) or die('Error: cannot open file'); while ($file = readdir($dp)) { if ($file != '.' && $file != '..') { $fileData = pathinfo($file); if (in_array($fileData['extension'], $photosExt)) { $photoList[] = "$photosDir/$file"; // file includes as an array } } } closedir($dp); }else { die('ERROR: directory dosent exists'); } //itarate over photo list //display each image and file name if (count($photoList)>0) { for ($x=0; $x <count($photoList) ; $x++) { ?> <li> <input type="checkbox" name="check" value="<?php echo $photoList[$x] ?>"> <img src="<?php echo $photoList[$x]; ?>" class="imagegrid"/> <div> <?php echo 'Image Name: '. basename($photoList[$x]); ?><br> <?php echo 'Image Size: '. round(filesize($photoList[$x])/1024) . 'KB'; ?> </div> </li> <?php } } else { die('ERROR: No image found'); } ?> </ul> </form> </body> </html>
and next, remove.php
<?php //for delete image //check the image //unlink the file if (isset($_POST['check']) && !empty($_POST['check'])) { //find the file $file = $_POST['check']; //delete from directory if(is_file($file)){ unlink($file); header('Location: manage.php'); echo $_POST['check']." has successfully deleted"; }else{ echo $_POST['check']." has not been found!"; } } else{ header('Location: manage.php'); echo "Select any image for delete"; } ?>
-
In manage.php I would change "check" to "check[]"
so from
<input type="checkbox" name="check" value="<?php echo $photoList[$x] ?>">
to
<input type="checkbox" name="check[]" value="<?php echo $photoList[$x] ?>">
Then in remove.php you can access all the fields that were selected by doing something like:
$files= $_POST['check']; foreach ($files as $file){ // Do something with each $file here }
I have not tested this. But the idea should be solid. Keep me posted.
-
Hey @MPG-Radio
How did that answer work out for you.
-
Pretty good but I haven't been able to get it working...:)