HTML Form Reload Problem


#1

In PHP, when an HTML Submit form is clicked, the database gets updated with the string in the form. When the user then chooses to reload this page with the refresh button of the browser (the browser warns you first that the page will repeat all actions done earlier), this string in the database gets updated AGAIN. In the case whereby comments are being made, that particular string (comment) gets written AGAIN and AGAIN in the database therefore some particular strings (comments) are stored as much times as the page was refreshed and that ruins the whole comment board when there are many identical comments.


#2

It’s really very easy to handle if you can structure your code properly.
If I have to share/detail my method here; then it’s gonna be a long article with function/methods and class…blah blah blah but I can explain a bit.

The conventional way is:
1-Post to server on this page,
2-Process on this page,
3-Return to this page(no HTTP_HEADER redirecting involved) and then
4-Report on this page (Display process message)

…now this will always perform a form re-post every time to refresh the page and might always re-process you action if you don’t validate against data available in your DB or directory. To bypass this headache in a simple and quick way, I will show you how to handle case 3;
Let’s try something like this:

if(!empty($_POST(‘your_post_identifier’))):
//do your redirection
header("Location: ". $YourRedirectLocation);

  //___perform all processes here before we terminate
  //To handle case 4 - you can always store your response message in a session and query the session on your landing page but always remember to unset the session after use.

 die();///terminate process --- Make sure you add this to end process on this condition

endif;

The code above will work fine if place @ the top of your script. The condition is only true for posted data with an input field ‘your_post_identifier’ not empty and you can always create a hidden field to handle that.

I hope this helps.


#3

A way to tackle it from the db end is you add an additional column to ur table (call it md5 with char 32) and make it unique. The field will contain the md5 value of your posted string:
insert into tbl (md5, comment) values (md5(’$string’), ‘$string’)
What this means is that if the content is submitted twice, the table wont allow it.
Hope it helps.


#4

@kehers
Thats a very good method using form_key.
I use that alot now for all posted form.