因为标题说我想阻止用户继续向我的数据库提交$_POST
数据。
现在我所拥有的是用于将表单数据提交到我的数据库的表单和简单类。问题是,如果用户提交数据并刷新浏览器,它将再次提交相同的数据。
我知道我可以通过meta或者使用标题来刷新页面,但我不想做一些如此愚蠢的事情,所以我想我可以做一些类似$_POST = null;
的事情,不确定这是否有效但是我实际上想保留所有的帖子数据,因为如果出现一些错误,我想用以前的帖子数据填充我的表格......
无论如何,我希望你们能得到我想做的事情并且可以帮助我一点点:D
答案 0 :(得分:4)
简单的解决方案是您应该在表单提交和处理后重定向用户。
您可以检查数据是否已成功提交并处理重定向用户,否则不会重定向它们,这可以保留$_POST
数据以重新填充字段。
这会阻止重新提交表单。
一般伪代码
if (isset($_POST['submit']))
{
if(validate() == true)
{
//passed the validation
// do further procession and insert into db
//redirect users to another page
header('location:someurl'); die();
}
else
{
$error='Validation failed';
// do not redirect keep on the same page
// so that you have $_POST to re populate fields
}
}
答案 1 :(得分:1)
我只想发布这段代码,这些代码可以在遇到某种情况时提供帮助:
A form is submitted and gets processed, but somewhere after the
processing code for the form is done some error occurs or
the internet connection of the client is lost and sees just a white page,
user is likely to refresh the page and will get that message box
that asks them if they want to re-post the data they sent.
For some users, they will try to re-post/re-send the form data
they filled up..
以下是示例代码:
# code near the very top of the page that processes the form
# check if $_POST had been set to session variable already
if (!isset($_SESSION['post_from_this_page'])){
$_SESSION['post_from_this_page'] = $_POST;
} else {
# if form has been submitted, let's compare
if (isset($_POST)) {
$comparison = array_diff($_POST, $_SESSION['post_from_this_page']);
if (!empty($comparison)){
# there are changes in the data. not a simple F5 or refresh
# posted data is not the same as previously posted data
// code to handle the posting goes here, or set :
$shouldprocessflag = true
} else {
# no changes, session variable (last submitted form of this page)
# is the same as what has just been posted
$shouldprocessflag = false;
# or perhaps use the code that @Shakti placed to redirect the user! :)
}
}
}
# pulled processing code from comparison check to this part
if ($shouldprocessflag = true) {
# start processing here
}
我认为这看起来不像评论格式,但我还是想分享这个想法。