Search code examples
phppostunlink

Get all vars in post and unlink files php


I'm making a script to list all the files in a directory. The user can then check a checkbox if they want to delete one of the files. The script I've got so far is below. The next step is on form post when the page reloads is to iterate over the delete$i in post and unlink (delete) the relevant files which have been checked. However I'm not quite sure of how to do this as I'm fairly new to php. There could be a varying number of files in the directory and I only want to delete the checked ones. Any tips on how this can be achieved would be greatly appreciated!

//directory to list the files from
$directory = "";

//get all image files
$files = glob($directory . "*.*");

echo "<h2>Files available:</h2>";
echo "<ul>";
echo "<form action=\"\" method=\"post\">";
echo "<input type=\"hidden\" name=\"delete\" value=\"true\" />";

//interger count
$i = 0;

//print each file name except index.php
foreach($files as $file) {
    if ($file != "index.php") {
        echo "<li><input type=\"checkbox\" name=\"delete{$i}\" value=\"{$file}\" /> <a href=\"http://files.abc.com/{$file}\">http://files.abc.com/" . $file . "</a></li>";
        $i++;
    }
}
echo "<li><input type=\"submit\" value=\"Delete Selected Files\" /></li>";
echo "</form>";
echo "</ul>";

Solution

  • I would agree with Dagon, after submitting the values.. just do something like this:

    if(isset($_POST["delete"])) {
        foreach($_POST["delete"] as $val) {
            unlink($val);
        }
    }