在php中上传时如何在确认后覆盖文件

在php中上传时如何在确认后覆盖文件,php,file-upload,overwrite,Php,File Upload,Overwrite,当检查文件是否已经存在时,我尝试在提交后上载和覆盖文件。 因此,如果首先检查文件夹中是否已经存在文件,然后我会给出选项:“Dow you want overwrite it?”如果是,则应上载该文件并覆盖旧文件 这就是我到目前为止所做的: ... // file is ready to be uploaded $tmpFilePath = $_FILES['file']['tmp_name']; $newFilePath = $dir.'/' . $_FILES[

当检查文件是否已经存在时,我尝试在提交后上载和覆盖文件。 因此,如果首先检查文件夹中是否已经存在文件,然后我会给出选项:“Dow you want 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;                                   
 }
文件中\u 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>
文件已经存在!是否要覆盖它?

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

为什么
退出()
?我会动态重新加载页面;否则,有些东西会输出两次,这仍然不足以作为退出的理由。你不应该杀死脚本,因为你不知道如何控制它。因此,如果我理解正确:如果文件存在,请将文件上载到
tmp
文件夹。确认请求后,是否将文件从
tmp
文件夹移动到其最终目标?听起来很合乎逻辑……没错。您不能将文件保留在其原始临时位置,因为系统将自动删除它。