vendredi 21 février 2020

PHP Checkbox delete files from folder

I want to delete files from folder called "fajlovi". Multiple and singled delete should work. But it delete first file in folder (0 position in array of files in the folder). If I check any for files it will delete first 4 files instead files I checked. Here is the code:

    $a = glob("fajlovi/*");
    echo "<br>var_dump of \$a ------------------------<br><pre>";
    var_export($a);
    echo "</pre>end dump od \$a ------------------------<br><br>";
    echo "Number od files in the directory: " . count($a) . "<br>";

    echo "<form method='POST' action='" . $_SERVER['PHP_SELF'] . "'><table >";
    echo "<th>File name:</th><th>Size MB:</th><th>Delete:</th>";
    foreach ($a as $key => $value) {
        echo "<tr><td>" . $value . "</td>";
        echo "<td>" . round(filesize($value) / 1024 / 1024, 5) . " MB <br></td>";
        echo "<td><input type='checkbox' name='checked[]'>" . $img_number = $key + 1 . "</td>";
    }

    echo "<tr><td colspan=3><input type='submit' name='delete' value='Delete'></td></tr>";
    echo "</table></form>";


    if (isset($_POST['delete'])) {
        $checkbox = $_POST['checked'];
        for ($i = 0; $i <= count($a); $i++) {
            if (isset($checkbox[$i])) {
                if (unlink($a[$i])) {
                    echo "Successfully deleted file" . $a[$i] . "<br>";
                }
            }
        }
    }

    if (!empty($_POST['checked'])) {
        var_dump($_POST['checked']);
    }

1. This is screenshot of the page:

enter image description here

2.then I check images I want to delete:

enter image description here

3. After pressing Delete button, this is the result: enter image description here

4. And after entering the page again, we can see that wrong images are deleted:

enter image description here




Aucun commentaire:

Enregistrer un commentaire