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


7 Years
Discussion Span
Last Post by amac44

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

Then delete.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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.