0

So i'm working on a project where i have to upload something to a database. In my case i upload pictures. Now the problem is, if i upload a picture and refresh the page the picture gets uploaded again. If i upload 3 pictures then the last picture gets uploaded again and again every time i refresh the page.

?php
if (isset($_POST['upload'])){
    $target = "images/".basename($_FILES['image']['name']);

    $db = mysqli_connect("localhost", "root", "", "aawebprog");

    $image = $_FILES['image']['name'];
    $text = $_POST['text'];
    $uploader = $_SESSION['username'];

    if($text > 50){
        $msg = "You have to write at least 50 characters!";
    }

    $sql = "INSERT INTO pictures (image, text, uploader) VALUES ('$image', '$text', '$uploader')";
    mysqli_query($db,$sql);

    if (move_uploaded_file($_FILES['image']['tmp_name'], $target)){
        $msg = "Image upluaded succesfully";
    } else{
        $msg = "There was a problem during the upload, try again";
    }
    echo ("$msg");
}

?

Any ideas what can be the problem?

treyBake
  • 6,440
  • 6
  • 26
  • 57
  • **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson Jan 27 '20 at 16:43
  • **Never** get your web app to login to the database as root. Root can do whatever it likes, so on top of the SQL injection vulnerabilities this just leaves your database an open book for hackers. Instead create a separate user account specifically for this application which has only the permissions it actually _needs_ in order to work properly. Don't even use the root account as a shortcut during development or testing, because you need to test your account permissions as well - otherwise when you go live you might have unexpected errors relating to the user account setup. – ADyson Jan 27 '20 at 16:43
  • 1
    If you refresh the page directly after you've submitted a form, most browsers will ask you to confirm if you wish to submit the form again. Presumably, you pressed "yes" which is why you're seeing that behaviour - you're sending the same data to the server again. It's hard to see how else it could be happening. – ADyson Jan 27 '20 at 16:44
  • You need to do a `header("Location: ...")` when the upload is successful from within the `if (isset($_POST['upload'])){...}` block. – marekful Jan 27 '20 at 16:46

0 Answers0