php 中上传期间确认后如何覆盖文件

how to overwrite a file after confirmation during upload in php

我在检查文件是否已存在时尝试在提交后上传并覆盖文件。 因此,如果首先检查文件夹中是否已存在文件,然后我将给出选项:"Dow you want to overwrite it?" 如果是,则应上传文件并覆盖旧文件。

这是我目前拥有的:

...
// file is ready to be uploaded    
$tmpFilePath = $_FILES['file']['tmp_name'];            
$newFilePath = $dir.'/' . $_FILES['file']['name'];

// check if file already exists
if(file_exists($dir.'/' . $_FILES['file']['name'])) {
        include('includes/file_exists.php');
        exit;
 }

 //finally upload the file
 if(move_uploaded_file($tmpFilePath, $newFilePath)) {    
    include('includes/success.php'); // echo                
    exit;                                   
 }

file_exists.php中是这个代码:

<span>File already exists! Do you want to overwrite it?</span>
<form class="sfmform"  action="" method="post">
    <input type="hidden" name="overwrite" value="<?php echo $_FILES['file']['tmp_name']; ?>" />                             
    <input type="submit" class=" btn btn-primary" name="submitoverwrite" value="Yes"/>
</form>

(所有请求都由 AJAX 处理)

如果该文件已经存在,您需要做的是将上传的文件移动到一个临时位置(不能将其留在 tmp 中,因为它会被删除)和 return 回复这告诉 UI 您需要确认才能覆盖(或要求一个新名称)。当用户决定时,UI 必须向服务器发送新请求。当您处理这个新请求时,您将文件移动到最终位置。