简体   繁体   中英

Foreach always delete last file PHP

I want to add "delete file" button next to input field, and I want to delete every file in folder notes, with this buttons separatly. But foreach ALWAYS delete last file . How to fix that? And why foreach always choose last file in array?

<form method="post" action="file_operation.php" id="delete_form">
<?php
$scan = scandir('notes/');

foreach($scan as $file)
{
    if (!is_dir("notes/$file"))
    {

        ?>
        <?php //echo $file.'<br>'; ?>
        <div class="col-md-6">
        <input type="text" name="file_name" placeholder="" value="<?php echo $file; ?>">
        <input type="submit" value="Delete File" name="delete_file">

        </div>
        <?
    }
}
?>

</form>

file operation source

if(isset($_POST['delete_file']))
{
 $file_name=$_POST['file_name'];
 $folder="notes/";
 #$ext=".txt";
 $ext='';
 $file_name=$folder."".$file_name."".$ext;
  echo "file ".$file_name." deleted";
  #exit();
 unlink($file_name);

}

You have lots of inputs with the same name. When you submit the form, the value of $_POST['file_name'] will be the value of the last input named file_name . That's why it always deletes the last file.

I would suggest using a button instead of an input. That way you can assign a value to the button so you can easily get the value of the clicked button in $_POST .

<?php echo $file ?>
<button type="submit" name="delete_file" value="<?php echo $file ?>">
    Delete File
</button>

Then in your submit handler:

if(isset($_POST['delete_file']))
{
    // now the submit button has a value of the file name to delete
    $file_name = $_POST['delete_file'];
    // ...

I'd also suggest validating the file name to make sure it's something that really should be deleted. As it is, someone could post any value they wanted and potentially delete something that shouldn't be deleted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM