Php 从表单上载文件时,如何覆盖服务器上的文件?

Php 从表单上载文件时,如何覆盖服务器上的文件?,php,html,Php,Html,必须删除以前提交的文件并用新文件替换,而不是创建新文件 <form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="attachment" id="attachment" onchange="document.getElementById('moreUploadsLink').style.display = 'block';" />

必须删除以前提交的文件并用新文件替换,而不是创建新文件

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="attachment" id="attachment" onchange="document.getElementById('moreUploadsLink').style.display = 'block';" />
    <input type="submit" value="Submit" name="submit">
</form>

upload.php

<?php
    $target_dir = "uploads/";
    $target_file = $target_dir .  date('d_m_Y_H_i_s') . '_'. $_FILES["attachment"]["name"];
    $uploadOk = 1;
    $fileType = pathinfo($target_file, PATHINFO_EXTENSION);

    // Move the file
    move_uploaded_file($_FILES["attachment"]["tmp_name"], $target_file);
?>

PHP上载然后写入文件:

<?php
$target_dir = "uploads/";
$target_file = $target_dir .  date('d_m_Y_H_i_s') . '_'.$_FILES["attachment"]["name"];
$uploadOk = 1;
$fileType = pathinfo($target_file, PATHINFO_EXTENSION);

// Move the file
move_uploaded_file($_FILES["attachment"]["tmp_name"], $target_file);

$file = fopen($target_file,"w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);
?>

您基本上需要做两件事:

  • 跟踪“上一个”文件
  • 删除跟踪的文件
每当用户上载新文件时,将其存储为他们上载的最后一个文件。会话状态似乎是跟踪这一情况的合理场所,至少目前是这样:

$_SESSION['lastFile'] = $target_file;
然后,每当用户上载另一个文件时,也要在更新之前删除最后一个文件:

if (isset($_SESSION['lastFile'])) {
    // This would be a good place to validate the file path first.
    // Make sure it exists, authorize the user before deleting it, etc.
    unlink($_SESSION['lastFile']);
}

如果要跟踪会话状态范围之外的“上一个文件”(例如,在重新启动web服务器时),则需要在该用户的数据库记录中跟踪“上一个文件”。

这取决于您如何持久化事务。用户是否已登录?上传的上下文是否仅限于该文件?对于临时事务(会话),您可以存储有关用户的信息,以指示应替换文件而不是将其添加到集合中。您在何处/如何跟踪“上一次提交”是什么?您可以像保存文件一样轻松地删除文件。当前您正在保存用户发送的文件。你在哪里删除“上一个”文件?@David:我还没有删除文件。我只是不知道如何以最佳方式实现所需的功能。我很少使用php。如果这个问题听起来太简单,很抱歉。你需要对她进行某种用户跟踪,或者如果你不关心以前的文件,请删除其中的任何内容并上载新文件(始终为1个文件),我应该将$\u会话['lastFile']=$target\u文件放在哪里@克劳斯:我想,在你已经拥有的代码即将结束时。它显然需要在删除之后以及定义
$target\u file
之后。我可能会在文件保存后再保存它,这样,如果保存文件时出错,您就不会删除以前的值。