I'm creating a form and using it to get data input to send to a MySQL database via php. If someone hits refresh on the page Firefox ressends the last set of information to the php page which in turn sends it to the database. Is there anyway to prevent this?
6 Answers
To fix that problem, there exists Post/Redirect/Get pattern you need to follow :)
Post/Redirect/Get (PRG) is a common design pattern for web developers to help avoid certain duplicate form submissions and allow user agents to behave more intuitively with bookmarks and the refresh button.
Comments
You need to do a redirect to the same page:
$current_url = (empty($_SERVER['HTTPS']) ? "http://" : "https://") . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; header ('Location: ' . $current_url); exit (); 5 Comments
The usual way to do this is to use a redirect.
You get the request, use the data it contains to load your database or whatever, and then perform a redirect (I think you're supposed to use a 303 redirect for this, but I've heard of a lot of people using 302s to avoid certain browser glitches).
The net effect of this is that there was no POST data sent when the redirect occurred, so refreshing can't cause it to be resent and screw up your application/database.
Comments
If you don't like any of the above and are using JQUERY. You could do a simple load or ajax function to send the information to your script.
This will erase any chance of duplicate sending and you no page reload. I like this method best, it's fast and easy.
Another solution you can do is have your form send to another page, a bit like this:
<form action="chat_server.php" method="post"> Message: <input type="text" name="message" /> <input type="submit" /> </form> On the chat_server.php file, you do what you need to do with the data and at the end, you do
echo '<meta http-equiv="REFRESH" content="0; url=chat.php" />'; Give it a try, should get rid of your problem.