Unset post variables after form submission
Here's a nice method I use to keep users from submiting the same data twice, which will also prevent the page from adding the same record to the database when reload.
// First IF
if ($_SESSION['dup_comment_body'] == $_POST['comment_body']) {
echo 'You already entered that.';
} else {
// Second IF
if ($_POST['comment_body']) {
// Run your query here
$_SESSION['dup_comment_body'] = $_POST['comment_body'];
header('location:'.$_SERVER['REQUEST_URI'].'');
}
}
The first IF
checks to see if the $_POST
is equal to the last thing they typed ($_SESSION
). If it's not the same it runs the next IF
to test if the $_POST
variable is not empty. Inside the last IF
towards the bottom it sets $_SESSION['dup_comment_body']
to equal the $_POST
. So next time the first IF
runs and the $_POST
is the same, they will get the message "You already entered that.". Hope this helps!
The problem you are facing above specifically can (and should) be solved with Post/Redirect/Get. Unsetting _POST
on the php side would be ineffective since the problem is it is a separate request.
You also have to deal with double-clicking of submission buttons. You can solve this on the client side by disabling form submission after the button click, or by putting a random token in the form and storing that token in the session. The token will be accepted only once (session keeps track of whether the token has been posted).
Use an intermediate page to do the operations and then redirect.
For example:
mypage.php --> the page with the form
dostuff.php --> receives the form data and makes operations, then redirects to any other page.
To do a redirect:
Put this line on the top of "dostuff.php": header("Location: mypage.php");
The post/redirect/get is a good option as some posters have already mentioned.
One another way I can think of is to set a session in the dostuff.php page to indicate that the posting has already been done. Check this session var each time to see if the page is being loaded again because of a page refresh.
<?php
session_start();
if(isset($_SESSION['indicator']))
{
/*
dont do anything because session indicator says
that the processing was already done..
you might want to redirect to a new url here..
*/
}
else
{
/*
first set session indicator so that subsequent
process requests will be ignored
*/
$_SESSION['indicator'] = "processed";
//process the request here..
}
?>
In the page you redirect to, unset the session var so that the form can be resubmitted again afresh, making it a new post operation. This will allow new form posts but will prevent post operations due to page refresh