Jack Maessen
Jack Maessen

Reputation: 1864

how to overwrite a file after confirmation during upload in php

I am trying to upload and overwrite a file after submit when checked if file already exists. So if first check if a file already exists in a folder, and then i will give the option: "Dow you want to overwrite it?" If YES, the file should be uploaded and overwrite the old one.

This is what i have so far:

...
// 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;                                   
 }

In file_exists.php is this code:

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

(all requests are handled by AJAX)

Upvotes: 1

Views: 449

Answers (1)

Joni
Joni

Reputation: 111259

If the file already exists, what you'll have to do is move the uploaded file to a temporary location (can't leave it in tmp because it'll get deleted) and return a response that tells the UI that you need confirmation to overwrite (or ask for a new name). When the user decides, the UI has to send a new request to the server. When you handle this new request, you move the file to the final location.

Upvotes: 3

Related Questions