PHP 使用 PHP_SELF 检测页面是否重新加载
我有一个使用更新数据重新加载页面的表单:
<form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
...
<input type="submit" name="Submit" value="Update data">
</form>
当页面更新时,我想显示一条消息“数据已更新”。我相信Referer有类似的事情,但不记得了。
顺便说一句,我还在使用:
if (isset($_POST['Submit'])) {
// prevent resending data
header("Location: " . $_SERVER['PHP_SELF']);
}
以避免用户单击后退按钮时烦人的重新发送数据消息。这是正确的吗?
I have a form that reloads the page with the updated data:
<form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
...
<input type="submit" name="Submit" value="Update data">
</form>
When the page is updated I want to display a message "Data updated". There was something like this with Referer I beleve, but can't remember.
btw I am also using:
if (isset($_POST['Submit'])) {
// prevent resending data
header("Location: " . $_SERVER['PHP_SELF']);
}
to avoid the annoying resending data message when the user clicks the back button. Is this correct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您想绝对确定表单已提交,您可以将变量存储在 会话:
不太可靠,但也可以使用
$_SERVER['HTTP_REFERER']
来检测访问者来自哪个页面。If you want to be absolutely sure that a form was submitted, you can store a variable in a session:
Less reliable but also possible is the use of
$_SERVER['HTTP_REFERER']
to detect what page the visitor came from.你可以做这样的事情
......重定向到 self,但带有额外的信息 - “?updated=true”(或 **&**updated=true 如果 PHP_SELF 已包含查询字符串)
b.根据此额外信息,显示文本。
...是的,您的重定向是防止重新提交的有效方法
You could do something like this ...
a. redirect to self, but with an extra piece of information - "?updated=true" (or **&**updated=true if PHP_SELF already contains a query string)
b. Based on this extra information, display the text.
... and yes, your redirect is a valid way to prevent resubmision
防止“重新发送数据”消息的普遍接受的方法是使用 Post-Redirect-获取模式。
理想情况下,您不应使用同一页面来显示结果并处理表单。我建议将“数据已更新”移动到表单验证通过后重定向到的单独页面。
这样,浏览器上的“后退”按钮对用户来说就可以直观地运行,而不会出现那些烦人的消息。
另外,从技术上讲,$_SERVER“referer”值可以被欺骗,因此您不应该总是依赖它。
A generally accepted way to prevent the "resend data" message is to use the Post-Redirect-Get pattern.
Ideally you shouldn't be using the same page to display results and also process the form. I would suggest moving "Data updated" to a separate page that you redirect to after the form validation has passed.
This way, the Back button on the browser behaves intuitively for the user without those annoying messages.
Also, technically the $_SERVER "referer" value can be spoofed so you shouldn't always rely on it.
您几乎可以使用您正在使用的东西:
为什么不这样做呢?
You can just use what you're using pretty much:
Why not do that?