2

So, I'm working on a commenting script. It works fine when you post a comment, but I found that when you refresh the page, even though the text field is empty, it still posts the same comment. I understand that this is because I've already sent the variable to $_POST, and it's simply inserting that value in to the database, but how do I avoid this issue? Thanks in advance, and here is my code: (Assume that $username and $image are already set)

if (isset($_POST['text']) && !empty($_POST['text'])) { $text = $_POST['text']; $timeStamp = time(); mysql_query("INSERT INTO comments VALUES ('$image','$username','$text','$timeStamp')"); } 

And the HTML:

 <form method = "post" action = "/view.php?image=$image" /> <input type = "text" name = "text" maxlength = "100" /> <input type = "submit" value = "Add Comment" /> </form> 

3 Answers 3

1

The easiest way to avoid that, is redirecting after a successful database operation:

... mysql_query("INSERT INTO comments VALUES ('$image','$username','$text','$timeStamp')"); // error handling header('Location: /some/where'); 

Apart from that, you really need to switch to PDO / prepared statements to avoid sql injection problems.

Sign up to request clarification or add additional context in comments.

12 Comments

As in sanitizing my values? I have that covered, I just didn't want to add it in to the question.
@Jack Stone Yes, but the mysql_* are being deprecated as well, so switching is a good idea for that as well.
Another thing about your code, I just think that it would be a bad user experience to redirect them every single time a comment is posted. Is there any other way of doing this?
@Jack Stone The user doesn't have to notice, it can be to the same page but the difference is that it will be a GET request so that a reload does nothing except reloading the page and the back-button still takes them to the previous page (the form).
So it would be a parallel commenting page, just without the form?
|
1

Are you posting to the same page that you are viewing the comments? If so you could probably post to /a_page_where_i_submit_things.php then redirect back to the page where the comments are. I believe that will work.

1 Comment

But if I'm trying to post it to the same page, why would I want to do that?
1

The easy way:

After saving to database, reload your page:

header('Location: comment-form.php'); 

This will make the browser "forget" the form submit.

The correct way:

Generate a nonce and add it as hidden input in your form. When the form submits, make sure $_POST['nonce'] matches with $nonce in your script.

How to create and use nonces

Comments