如何在 PHP 中制作取消链接按钮


How can I make a unlink button in PHP

我有一个PHP脚本,你可以在其中上传文件。这些文件将列出,并转换为下载链接。我需要的最后一件事是每个列表项的删除按钮。这样

  • 测试.txt X

(大 X 应该是删除按钮)。

这是我到目前为止的代码。

<?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>

我对PHP很陌生,所以我希望有人可以用简单的语言解释我是如何工作的。

我需要的最后一件事是每个列表项的删除按钮

通过表单发布值:

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

然后在delete.php,引用$_POST['file_id']

另一种方法是将while循环包装在以下形式中:

<form method="post" action="delete.php">
  <?php while(...): ?>
    <button type="submit" name="file_id" value="some_value">&times;</button>
  <?php endwhile; ?>
</form>

您可以添加 X 链接以引用要删除的文件,即

$thelist .= '<li><a download="'.$file.'"href="uploads/'.$file.'">'.$file.'  </a> <a href="delete.php?item='.$file.'"> X </a></li>';

然后在删除页面上,您可以添加取消链接代码以删除文件

$file = $_GET['item'];
if (!unlink($file))
  {
  echo ("Error deleting $file");
  }
else
  {
  echo ("Deleted $file");
}

这是如何去做的基本思想。但为了安全起见,您可以在参数上加密 url 文件名,即

base64_encode($file)

在删除页面上,您可以对其进行解码

base64_decode($_GET["item"])

为了创建删除该项目的请求,您可以例如:

<form action="delete.php" method="POST">
  <input type="hidden" name="csrf_token" value="$csrf_token">
  <input type="hidden" name="file" value="$file">     
  <button type="submit">X</button>
</form>

基本上$csrf_token是一个与会话绑定的安全随机令牌,服务器应在处理删除请求之前对其进行验证。(有关CSRF安全问题的更新@PeeHaa提及。(如果支持,可以使用方法 DELETE。