-2

i have this script, to show alla images in a folder and also i have a delete button/link under all the thumbnails. I click this delete button/link to display a Sweet alert 2 confirmation box, and if i click OK(Ja, Radera!) the unlink.php file is called and the images are deleted. But my problem is that when i click delete button/link the wrong image is deleted. Can any one see whats wrong please. Thank you.

<div id="thumbs_gallery">
            //----------PART ONE START - SHOW ALL IMAGES IN FOLDER----------//
            <?php
                $directory = 'images/';
                $thumbsdir = 'images/thumbs';
                $allowed_types = array('jpg', 'JPG', 'JPEG', 'jpeg', 'gif', 'PNG', 'png');
                $fileNames = $files = $file_parts = array();
                $ext = '';
                $title = '$file';
                $i = 0;

                $toMatch = "{$directory}*.{".implode(',', $allowed_types).'}';
                $fileNames = glob($toMatch, GLOB_NOSORT | GLOB_BRACE);  

                    foreach($fileNames as $file) {
                        $f = explode('/', $file);
                        $fileName = end($f);
                        $files[$fileName] = filemtime($file);
                    }

                    arsort($files);

                    foreach(array_keys($files) as $file)
                    {
                        $file_parts = explode('.',$file);
                        $ext = strtolower(array_pop($file_parts));

                        $title = implode('.',$file_parts);
                        $title = htmlspecialchars($title);
                //----------PART ONE END----------//

                //----------PART TWO START - SHOW THUMBNAILS AND DELETE BUTTON/LINK----------//
                echo '
                <div class="thumbs_gallery_img" style="background:url('.$thumbsdir.'/'.$file.') no-repeat 50% 50%;"> //Show thumbnails
                <a href="'.$directory.''.$file.'" title="'.$title.'">'.$title.'</a> // Link to big image
                <div class="unlink"><i class="fas fa-trash-alt fa-2x"></i><a href="unlink.php?filename='.$file.'"></a></div> //Delete button/link
                </div>';
                //----------PART TWO END----------//

                //----------PART TRHEE START - PREVENT DEFAULT ON DELETE BUTTON/LINK AND RUN SWEET ALERT 2, AND THE UNLINK.PHP FILE.----------//
                echo '<script>
                $(".unlink a").on("click", function(e) {
                // Do not run the unlink.php file on link click.
                e.preventDefault();
                    // Run the Sweet Alert 2 code.
                    swal({
                    title: "Radera denna bild?",
                    text: "Klicka på Ja om du vill radera denna bild.",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#d33",
                    cancelButtonColor: "#3085d6",
                    confirmButtonText: "Ja, Radera!",
                    cancelButtonText: "Nej, Avbryt!",
                    }).then((result) => {
                if (result.value) {
                // If confirm run the unlink.php file.
                    window.location.href ="unlink.php?filename='.$file.'";
                } else if (
                    result.dismiss === swal.DismissReason.cancel
                ) {
                // If cancel do nothing (stay on same page).
                }
                })
                })
                </script>';

                $i++;               
                }
            ?>
            //----------PART THREE END----------//
        </div>

       //THIS IS THE CODE IN THE unlink.php file:
   <?php
    $img_to_delete = $_GET['filename'];

    unlink('images/thumbs/'.$img_to_delete);
    unlink('images/'.$img_to_delete);
    header('location: dropzone.php');
    ?>
Funk Forty Niner
  • 73,764
  • 15
  • 63
  • 131
Patrik Idén
  • 355
  • 2
  • 12

1 Answers1

1

Problem

Is that you have many duplicated js functions <script>swal({})</script> bound to one selector .unlink a. You are adding a duplicate sweet alert function for each file that can be deleted, since they are all bound to the same selector the first one is executed when you click any delete link. Whichever file is referenced in that function gets deleted.

Solution

Instead of duplicating this sweet alert function inside the foreach loop you are using to generate the links. You could add a data tag to each link with the filename and then have one js function responsible for the handling the delete. Something like this:

foreach (array_keys($files) as $file) {
   //add whatever filename modifications here
   echo '<a href="#" class="unlink" data-file="'.$file.'">Delete</a>';
}

<script>
  $("a.unlink").on("click", function(e) {
     // Run the Sweet Alert 2 code.
     swal({
       title: "Radera denna bild?",
       text: "Klicka på Ja om du vill radera denna bild.",
       type: "warning",
       showCancelButton: true,
       confirmButtonColor: "#d33",
       cancelButtonColor: "#3085d6",
       confirmButtonText: "Ja, Radera!",
       cancelButtonText: "Nej, Avbryt!",
     }).then((result) => {
        if (result.value) {
           // If confirm run the unlink.php file.
           window.location.href ="unlink.php?filename="+$(this).data('file');
        } else if (
           result.dismiss === swal.DismissReason.cancel
        ) {
            // If cancel do nothing (stay on same page).
        }
     })
 })</script>
flint
  • 325
  • 3
  • 14