防止刷新时插入重复记录而不重定向

发布于 2024-10-15 03:20:17 字数 380 浏览 3 评论 0原文

我有这样的脚本:

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);
}

用户提交评论并刷新页面后,他会收到“您将重新发送帖子数据”警告。如果用户接受,它将重新插入用户评论。

我知道我可以通过添加使用 header 函数并将成员重定向到同一页面来防止这种情况。是否可以在不重定向成员的情况下解决此问题?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

笑梦风尘 2024-10-22 03:20:17

不会。您可以执行 post-redirect-get 或后续刷新向用户呈现此对话框。

如果您选择不执行 PRG,您需要以某种方式检测提交是否重复。一种简单的方法是用随机散列/数字(例如称为令牌)注入隐藏参数。提交后,您必须检查您期望的令牌(您可能已将其存储在 http 会话中)是否与其他 POST 参数一起发送。有效提交后,您将删除/使该令牌失效。这样,当 POST 发出无法识别的令牌时,它很可能是重复或过期的请求。

如果您正确实施这一点,那么您还可以使您的应用程序免受 csrf 攻击。

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.

写给空气的情书 2024-10-22 03:20:17

成功提交后,您可以设置一些会话变量。对于每次提交,您都会检查变量是否已设置,然后插入数据。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文