Kilisi Kilisi - 2 months ago 28
PHP Question

Php list files in directory with option to delete

I have download-ui.php which has this code which excludes some and lists all the other files in a directory, then sorts them and gives each a checkbox.

<?php
$files = array();
$dir = opendir('.');
while(false != ($file = readdir($dir))) {
if(($file != ".") and ($file != "..") and ($file != "download-ui.php") and ($file != "error_log") and ($file != "favicon.ico")) {
$files[] = $file;
}
}

natcasesort($files);

foreach ($files as $file) {
echo '<li class="browse-file">
<div class="select-all-col"><input name="select[]" type="checkbox" class="select" value="'.$file.'"/></div>
<div class="file-name-col"><a href="download-ui.php?name='.$folderName."/".$file.'" style="cursor: pointer;">'.$file.'</a></div>
<br />
</li>';
}
?>


I'm trying to work out how to then get the checkbox values so that these files if checked can be deleted using
unlink()
.

I know I need a form, but need an assist with syntax and capturing the values for the form, this is what I have so far.

<form id="delete" action="delete.php" method="post">
<button type="submit" form="delete" value="Submit">Submit</button>
<input name="select[]" type="checkbox" class="select" value="'.$file.'"/>
</form>


Then for delete.php I have

<?php?
foreach ($_post['select[]'] as $file) {
if(file_exists($file)) {
unlink($file);
}
elseif(is_dir($file)) {
rmdir($file);
}
}
echo "Files deleted successfully.";
?>


I think my problem is the input
<input name="select[]" type="checkbox" class="select" value="'.$file.'"/>


The error I'm getting with this latest effort is
PHP Warning: Invalid argument supplied for foreach()
in delete.php

Answer

You want to loop through each item of $_POST['select'], so your foreach should say:

foreach ($_POST['select'] as $file) {

}

Notice that POST is capitalized and select has no array brackets.

Comments