I have this bit of script:
if (isset($_POST['comment_posted'])) {
$user_comment = mysql_real_escape_string($_POST['user_comment']);
$add_user_comment = Event::addUserComment($id,$user->user_id,$user_comment);
}
After a user submits his comment, and refreshes the page, he is being presented with the "you are going to resend the post data" warning. And if the user accepts, it will re-insert the user comment.
I understand that I can prevent that by adding using the header
function and redirect the member to the same page. Is it possible to solve this issue without redirecting the member?
No. You'll either do a post-redirect-get or subsequent refreshes will present this dialog to the user.
In case you chose not to do a PRG, you need to somehow detect that the submission is duplicate. One easy way is to have injected a hidden parameter with a random hash/number (e.g called token). Upon submission you'll have to check that the token you expect (which you'll have probably stored in the http session) is being sent together with the other POST parameters. On valid submission you'll remove/invalidate this token. That way when a POST comes which a non recognised token then it's most probably a duplicate or out of date request.
If you implement this correctly then you'll also make your application proof to csrf attacks.
You could set some session variable after successful submission. For each submission you check whether the variable is set or not, on you make an insertion of data.
来源:https://stackoverflow.com/questions/4842801/prevent-duplicate-record-insertion-on-refresh-without-redirecting