Hi,

I have script below that scans a folder and lists the contents into a drop down box. What I want to do is then select the file and press the delete button. Which removes the file from the folder. I do realise you can use unlink to remove the file, but I am not totally sure how to incorporate this into the script.

Any help would be appreciated.

<h2>Delete existing File</h2>
<p><select name="id"></p>
<option value="">-- Choose a file --</option>
<?php
echo "<form>";
//Looks into the directory and returns the files, no subdirectories
echo "<select name='yourfiles'>";

//The path to the file directory
$dirpath = "uploads";
$dh = opendir($dirpath);
while (false !== ($file = readdir($dh))) {

//Don't list subdirectories
if (!is_dir("$dirpath/$file")) {

//Truncate the file extension and capitalize the first letter
echo "<option value='$file'>" . htmlspecialchars(ucfirst(preg_replace('/\..*$/', '', $file))) . '</option>';}

}

echo "</select></p>";
echo '<p><input type="submit" value="Delete" class="submit" />';
echo "</form>";

closedir($dh);

?>

add an action and method to form:
<form action="delete.php" method="post">

Then delete.php

<?php
$dirpath = "uploads";
$file_to_delete = $_POST['yourfiles']; //as named in your <select>
if ( unlink ($dirpath.'/'.$file_to_delete) ) {
  echo $file_to_delete . " deleted.";
}
else {
  echo "Error.";
}
?>

I'm sure more error checking would be a good idea. Feeding user input directly into an OS or database operation without validating the input is not a good idea.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.