I have a simple form that submits text to my SQL table. The problem is that after the user submits the text, they can refresh the page and the data gets submitted again with
Use header and redirect the page.
header("Location:your_page.php");
You can redirect to same page or different page.
Unset $_POST after inserting it to Database.
unset($_POST);
I use this javascript line to block the pop up asking for form resubmission on refresh once the form is submitted.
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
Just place this line at the footer of your file and see the magic
You should really use a Post Redirect Get pattern for handling this but if you've somehow ended up in a position where PRG isn't viable (e.g. the form itself is in an include, preventing redirects) you can hash some of the request parameters to make a string based on the content and then check that you haven't sent it already.
//create digest of the form submission:
$messageIdent = md5($_POST['name'] . $_POST['email'] . $_POST['phone'] . $_POST['comment']);
//and check it against the stored value:
$sessionMessageIdent = isset($_SESSION['messageIdent'])?$_SESSION['messageIdent']:'';
if($messageIdent!=$sessionMessageIdent){//if its different:
//save the session var:
$_SESSION['messageIdent'] = $messageIdent;
//and...
do_your_thang();
} else {
//you've sent this already!
}
Basically, you need to redirect out of that page but it still can make a problem while your internet slow (Redirect header from serverside)
Example of basic scenario :
Way to solve
Client side
Server side
Using the Post/Redirect/Get pattern from Keverw answer is a good idea. However, you are not able to stay on your page (and I think this was what you were asking for?) In addition, it may sometimes fail:
If a web user refreshes before the initial submission has completed because of server lag, resulting in a duplicate HTTP POST request in certain user agents.
Another option would be to store in a session if text should be written to your SQL database like this:
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
$_SESSION['writeSQL'] = true;
}
else
{
if(isset($_SESSION['writeSQL']) && $_SESSION['writeSQL'])
{
$_SESSION['writeSQL'] = false;
/* save $_POST values into SQL */
}
}
Why not just use the $_POST['submit']
variable as a logical statement in order to save whatever is in the form. You can always redirect to the same page (In case they refresh, and when they hit go back
in the browser, the submit post variable wouldn't be set anymore. Just make sure your submit button has a name
and id
of submit
.