I want the user to be able to delete a file by clicking on a checkbox and submitting the form.
Somewhere in the header:
foreach ($_POST ['files'] ['deleteFile'] as $value)
{
unlink ($value);
$fileError = '¡Éxito!';
}
Somewhere in the body:
<form enctype="multipart/form-data" method="post" name="files">
<!-- No action attribute was added as the form is processed in the same file -->
<?php
foreach (glob ('files/*.*') as $file)
{
echo $file . '<input name="deleteFile" type="checkbox" value="' . $file . '">';
}
?>
<input type="submit" value="Confirmar">
</form>
Because you don't have a key in the $_POST
super-global called files
. Assuming you want the values of the selected checkboxes to be added to the $_POST
array, you should use the following code:
<form method="post">
<?php
foreach (glob ('files/*.*') as $file)
{
echo $file . '<input name="deleteFile[]" type="checkbox" value="' . $file . '">';
}
?>
<input type="submit" value="Confirmar" />
</form>
Note that we call the field deleteFile[]
. The square brackets tell PHP to handle all fields with the same name as an array. Now, we can use a foreach()
to loop through each value as follows:
foreach ($_POST['deleteFile'] as $value)
{
unlink ($value); // or you might need unlink('files/'.$value);
$fileError = '¡Éxito!';
}
Please be aware that you do not need the enctype
attribute for this type of request. In addition, PHP is not like JS. The name of the form does not relate to the values in $_POST
.