Using checkbox To Delete A File


Can you please tell me how can I use checkbox to delete a certain file after
I open and read from a certain directory using the variable $file - includes each file
that is inside this dir.

Hmmm ? What do you mean ?

Do you want to delete a file on the server and represent a list to the user with all files on that server ?

Or soemthing else ?

Well, its like that - I opened a certain directory and then I read all the files that are
located inside the dir and I output a list with all the files and near each file I add a checkbox
with value=file_path.

I need to know how could I use the checkbox so when
the user select it and he clicks on a delete button the file will be deleted from the

Ah, ok. On the server that is. Good.

getting the value of that checkbox can be done with


That value will always be empty if it wasn’t checked, and will have the path if it was checked.

So just loop through all your boxes and unlink() the files for the checkboxes that aren’t empty.

You’ve explained the part that I already know :stuck_out_tongue: the part that I don’t know is how to loop
through all the checkboxes and delete only the checked ones, can you tell me how?

Oh, hehe :stuck_out_tongue:

let’s assume you named them all file in your form:

foreach ($_POST['file'] as $filename) {
 // empty ones will be taken out with this IF
 if ($filename) {
   // You might print somethign too

Just to show you more detailed what kajakske said.

if(isset($_POST['submit'])) {
    foreach($_POST['file'] as $file) {
        if(isset($file)) {
            if (unlink($file)) {
                echo "Deletet the file: $file<br />";
            } else {
                echo "Didn't manage to delete the file: $file<br />";
<p><a href="<?php echo $_SERVER['PHP_SELF']; ?>">Reload</a></p>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Pick the files you want to delete:<br />
<input type="checkbox" name="file[]" value="file1.php" />file1.php<br />
<input type="checkbox" name="file[]" value="file2.php" />file2.php<br />
<input type="checkbox" name="file[]" value="file3.php" />file3.php<br />
<input type="checkbox" name="file[]" value="file4.php" />file4.php<br />
<input type="checkbox" name="file[]" value="file5.php" />file5.php<br />
<input type="checkbox" name="file[]" value="file6.php" />file6.php<br />
<input type="checkbox" name="file[]" value="file7.php" />file7.php<br />
<input type="checkbox" name="file[]" value="file8.php" />file8.php<br />
<button type="submit" name="submit">Send</button>
<button type="reset" name="reset">Reset</button>

HTH :slight_smile:


Thanks for your time and help guys, I finally fixed it and its working fine. :stuck_out_tongue: