Hi guys, I have a simple php script to upload file. I'm having some problem in creating confirmation before overwriting the file from new file upload.

Situation:
1. confirm() works if using file_exists BUT not overwrite the file or process the move_uploaded_file

assuming some tags are correct

uploadfile.php

<form enctype="multipart/form-data" action="addfile.php" method="POST" action="javascript:alert('success!');">
<td><label for="file">Choose File to Upload:</label></td>
        <td>
            <input type="file" name="upfile" id="upfile"> <br><br>
            <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
            <input type="hidden" name="fileuploaded">
        </td>
    </tr>
    <tr>
        <td></td>
        <td> 
            <input type="submit" name="submit" value="Add" class="pure-button pure-button-success" onclick="tellme();">
            <!-- <input type="submit" name="submit" value="Add" class="confirmLink"> -->
            <a href="index.php" ><button class="pure-button pure-button-secondary">Cancel</button></a>
</form>

addfile.php

<script type="text/javascript">
function tellme()
{
 alert("New File Added Successfully.");
 window.location = 'search.php';
}

function overwrite()
{
var r=confirm("Overwrite File?")
if (r==true)
  {
  alert("You pressed OK!")
  window.location = 'search.php';
  }
else
  {
  alert("You pressed Cancel!")
  window.location = 'new_file.php';
  }
}
</script>

if(!mysqli_query($con, $sql))
{
  die('Error ' . mysqli_error());
}

if (file_exists("files/" . $_FILES['upfile']['name']))
    {
        echo "<script type='text/javascript'>
            var answer = confirm(Overwrite? Y/N)
            if (answer)
            {
                <?php move_uploaded_file($_FILES['upfile']['tmp_name'],$target); ?>
            }
            </script>";
    }   
    else 
    {
        move_uploaded_file($_FILES['upfile']['tmp_name'],$target);
        echo "<script type='text/javascript'>tellme();</script>";

Thanks in advance! cheers!

Dani AI

Generated

As discovered, the symptom (confirm() shows but the file is still moved) comes from mixing server-side PHP and client-side JavaScript. PHP runs on the server and finishes before the browser ever shows a confirm dialog, so any call to move_uploaded_file() executed while building the page will have already run — echoing PHP into a JS string does not defer execution. 's echoed call suffers from that exact timing issue.

Two reliable patterns to fix this:

  1. Client-side pre-check (AJAX): intercept the form submit, send the chosen filename to a small server endpoint that returns whether the final path exists. If it exists, show confirm() and, on OK, add a hidden overwrite=1 and submit. On the server always require and verify that overwrite before replacing an existing file. Never rely only on client-side checks — always re-check on the server.

  2. Server two-step (recommended when you want to avoid re-upload): on initial POST, if the target exists, move the uploaded file to a server-controlled temporary filename (unique, in a tmp folder), save its metadata in session, and return a confirmation page. If the user confirms, rename/replace the final file and insert the DB row; if the user cancels, unlink the temp file. This guarantees the server holds the uploaded bytes while the user decides.

Always validate $_FILES['error'], check move_uploaded_file() return values, sanitize basename() to prevent traversal, ensure the target directory is writable, and protect the confirm flow with CSRF/session state so an attacker cannot force overwrites.

Recommended Answers

All 5 Replies

Where do you define the variable $target?

in addfile.php, thanks.

in addition to addfile.php

    $target = "files/";
    $target = $target . basename($_FILES['upfile']['name']);

    $currentDate = date("Y-m-d");
    $vtitle = $_POST['title'];
    $vfilename = ($_FILES['upfile']['name']);
    $vfiletype = $_FILES['upfile']['type'];
    $vfilesize = ($_FILES['upfile']['size'] / 1024);

    $con = mysqli_connect("localhost", "root", "pw", "db");
    if(mysqli_connect_errno())
    {
      echo "error connection" . mysqli_connect_error();
    }

    $sql = "INSERT INTO table (date,fld_title,fld_filename,fld_filetype,fld_filesize,fld_user) 
          VALUES ('$currentDate','$vtitle','$vfilename','$vfiletype','$vfilesize','$vuser')";

    if(!mysqli_query($con, $sql))
    {
      die('Error ' . mysqli_error());
    }

Here are the simplest code for addfile.php

<?php 
 $target = 'files/'.$_FILES['upfile']['name'];
if (file_exists("files/" . $_FILES['upfile']['name']))
    {
        echo "<script type='text/javascript'>
          var answer = confirm('Overwrite? Y/N');

        if (answer == true)
        {
            alert('You pressed OK!')
           var overwrite = ".move_uploaded_file($_FILES['upfile']['tmp_name'],$target)."
            if(overwrite == 1)
            {
                alert('File Overwrite successfully');
                window.location = 'search.php';
            }else alert('File Overwrite Failed'); window.location = 'new_file.php';
        }else alert('You pressed Cancel!'); window.location = 'new_file.php';
            </script>";
    }   
    else 
    {
         $ans = move_uploaded_file($_FILES['upfile']['tmp_name'],$target); 

        if($ans == 1)
        {
            echo "<script type='text/javascript'>alert('New File Added Successfully.');
 window.location = 'search.php';</script>";
        }else  echo "<script type='text/javascript'>alert('New File Added Failed.');</script>";

    }
?>

thank you, i will try to check this! cheers!

hi stevie, i tried your script, it works fine, but if i cancel still it executes the move upload file or still inserting the file.
thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.