1

I want to overwrite a file, if it already exists in the folder. Here is my code:

index.php

<form action="check.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <button type="submit" value="upload">Upload</button>
</form> 

check.php

if(isset($_FILES['file'])) {
    $file = $_FILES['file'];
    $target_file = 'files/'.basename($_FILES["file"]["name"]);
    if (file_exists($target_file)) {
        echo "File already exist";                  
        echo "<form action='overwrite.php' method='post'>
                <button type='submit'> Overwrite</button>
            </form>";
    } 
}

overwrite.php

move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
echo "The file is overwritten";

Update: I did a mistake in my question. Now I changed it. On check.php there should only be the statement "File already exists" and a button which directs to the overwrite.php and overwrite the file. (No second input field)

peace_love
  • 6,229
  • 11
  • 69
  • 157
  • In overwrite.php the global variable `$_FILES` is empty. – Daan Jul 23 '15 at 13:34
  • Check your script has permission to overwrite the file. Alternatively, create a unique string as the file name so you avoid this issue. – Liam Sorsby Jul 23 '15 at 13:40
  • possible duplicate of [PHP File upload and overwrite file with same name](http://stackoverflow.com/questions/8064618/php-file-upload-and-overwrite-file-with-same-name) – Liam Sorsby Jul 23 '15 at 13:42

2 Answers2

1

when you are creating the form again you need to specify enctype="multipart/form-data"

 echo "<form action='overwrite.php' method='post' enctype='multipart/form-data'>
        <input type='file' name='file'>
        <button type='submit'> Overwrite</button>
    </form>";

without enctype="multipart/form-data"it wont let you perform file upload operation

other than that name should not be a value it should be static so you can use it

Ben
  • 8,894
  • 7
  • 44
  • 80
Meenesh Jain
  • 2,532
  • 2
  • 19
  • 29
0

You're accessing $_FILES["file"] but, unless $target_file==="file", you're not finding anything.

Change the name attribute of the file upload from $target_file to just file:

        echo "<form action='overwrite.php' method='post'>
                <input type='file' name='file'>
                <button type='submit'> Overwrite</button>
            </form>";
Ben
  • 8,894
  • 7
  • 44
  • 80
  • What do you see when you use `var_dump($_FILES)`? – Ben Jul 23 '15 at 13:46
  • Sorry, I did a mistake in my question. On check.php there shouldn't be a new input field, just a button to say overwrite. So on my check.php should only be the statement "File already exists" and a button which directs to the overwrite.php and overwrite the file. – peace_love Jul 23 '15 at 13:54
  • Do you know how to get the code working without an input field on check.php? – peace_love Jul 23 '15 at 14:12