Deleting files with php

Hi Guys,

I am new to this place and wonder if anyone here could help. I have been working on a script that supposed to scan the contents of a folder and then display the results into a drop down box. I then then want to be able select the file a file and then delete it via delete button. This is where I am up to but it will just not delete the file. I just keep on getting undefined index on line 6 of delete.php

<h4>Delete existing File</h4>
<form method="post" action="deleted.php">
<p><select name="id"></p>
	<option value="">-- Choose a partner --</option>
<?php

echo "<form>";
//Looks into the directory and returns the files, no subdirectories
echo "<select name='yourfiles'>";

//The path to the file directory
$file = $_POST['yourfiles'];
$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" /></p>';
echo "</form>";


closedir($dh);

?

delete.php

<?php

ini_set('display_errors',1);

$dirpath = "uploads";
$file_to_delete = $_POST['yourfiles']; 
if ( unlink ($dirpath .'/'. $file_to_delete) ) {
  echo $file_to_delete . " deleted.";
}
else {
  echo "Error.";
}

?>

Any help on this would be appreciated.

Ahhh! It’s so clear when pointed out. It’s working now. Thanks for your help.

The first line of your PHP code is echo “<form>”… which shouldnt be there.

No, your code is a little muddled (particularly lines 3-9 of your first script) which might be causing you problems. To highlight an issue, you have two lots of opening form tags and two lots of opening select tags resulting in badly formed HTML from your script.

Tried what you said but still getting the following error:

Notice: Undefined index: yourfiles in …/delete.php on line 6

Warning: unlink(uploads/) [function.unlink]: Operation not permitted in …/delete.php on line 7
Error.

write echo “<form method=\“post\”>”;
instead of echo “<form>”;

Thanks for the reply. Sorry I am not sure what you mean, have I not declared the method as post on the first script?

Your form is not being sent via POST (it defaults to GET). Put method=“POST” into your form’s opening tag.