Kilisi Kilisi - 1 year ago 143
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.

$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;


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 />

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

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.'"/>

Then for delete.php I have

foreach ($_post['select[]'] as $file) {
if(file_exists($file)) {
elseif(is_dir($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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download