Prevent duplicate record insertion on refresh without redirecting

寵の児 提交于 2019-12-20 05:43:30

问题


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?


回答1:


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.




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!