Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a unlink button in PHP

Tags:

php

I have a PHP script where you can upload files. These files get listed, and are converted to a download link. The last thing that I need is a delete button for each list item. Like so

  • test.txt X

(The large X should be a delete button).

This is my code so far.

<?php

  if(isset($_FILES['file_array'])){
    $name_array = $_FILES['file_array']['name'];
    $tmp_name_array = $_FILES['file_array']['tmp_name'];
    $type_array = $_FILES['file_array']['type'];
    $size_array = $_FILES['file_array']['size'];
    $error_array = $_FILES['file_array']['error'];
    for($i = 0; $i < count($tmp_name_array); $i++){
        if(move_uploaded_file($tmp_name_array[$i], "uploads/".$name_array[$i])){
        } else {
            echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
        }
    }
  }


   $thelist = "";
   if ($handle = opendir('uploads')) {
       while (false !== ($file = readdir($handle))) {
           if ($file != "." && $file != "..") {
              $thelist .= '<li><a download="'.$file.'"href="uploads/'.$file.'">'.$file.'</a></li>';
           }
      }
    closedir($handle);
  }
?>

<h1>List:</h1>
<ul><?php echo $thelist; ?></ul>

Im quite new with PHP, so I that hope someone can explain me how it works in easy language.

like image 396
Stijn Westerhof Avatar asked Oct 30 '22 07:10

Stijn Westerhof


1 Answers

The last thing what I need is a delete button for each list item

Post the value via a form:

<form method="post" action="delete.php">
  <button type="submit" name="file_id" value="some_value">&times;</button>
</form>

And then in delete.php, reference $_POST['file_id'].

Another method is to wrap your while loop in the form:

<form method="post" action="delete.php">
  <?php while(...): ?>
    <button type="submit" name="file_id" value="some_value">&times;</button>
  <?php endwhile; ?>
</form>
like image 74
rybo111 Avatar answered Nov 15 '22 05:11

rybo111