Home  >  Article  >  Backend Development  >  ThinkPHP 防止表单重复提交的方法_php技巧

ThinkPHP 防止表单重复提交的方法_php技巧

WBOY
WBOYOriginal
2016-05-17 09:16:17950browse

然而有一种情况,是防止不了的:

用户提交表单以后,点击浏览器后退按钮返回表单页面,这个时候浏览器会直接从缓存中取出页面,因此token验证一定是通不过的。

网上有许多种办法可以绕过这个问题,比如用location.replace()方法来替换当前历史记录,但是这样仍然有瑕疵。极端的情况,若用户在页面间切换多次,那么多点几次后退按钮很可能又回到了上一个表单页面。

解决办法是在http头中设置Cache-Control: no-cache, no-store。然而我尝试了无论是在页面head中添加 还是在Action中输出 header("Cache-control: no-cache, no-store") 都无效。

ThinkPHP 防止表单重复提交的方法_php技巧

查找了很久,发现问题出在ThinkPHP的模板渲染机制上,打开 ThinkPHP/Lib/Think/Core/View.class.php 看第173行

header("Cache-control: private");  //支持页面回跳

原来TP为了支持页面回跳,强制在每个模板输出之前都发送了一个Cache-control: private的头,这可真是帮了倒忙了。

把这行注释掉,删除TP核心缓存,再试一次,发现HTTP响应头成功改变了

ThinkPHP 防止表单重复提交的方法_php技巧
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn