因此,標題說我想阻止用戶繼續向我的數據庫提交$_POST
數據。防止用戶提交相同的發佈數據
現在我已經是窗體數據提交到我的數據庫的窗體和簡單的類。問題是,如果用戶提交數據並刷新瀏覽器,它會再次提交相同的數據。
我知道我可以刷新我的自我與元或頁眉,但我不想做一些這麼愚蠢的東西,所以我想我可以做一些像$_POST = null;
不知道如果這樣的作品,但我真的想要保持所有數據後,如果因爲一些錯誤出現,我想填充我與以前的帖子數據形式...
反正我希望你們明白我想在這裏做,可以幫助我一點點:d
因此,標題說我想阻止用戶繼續向我的數據庫提交$_POST
數據。防止用戶提交相同的發佈數據
現在我已經是窗體數據提交到我的數據庫的窗體和簡單的類。問題是,如果用戶提交數據並刷新瀏覽器,它會再次提交相同的數據。
我知道我可以刷新我的自我與元或頁眉,但我不想做一些這麼愚蠢的東西,所以我想我可以做一些像$_POST = null;
不知道如果這樣的作品,但我真的想要保持所有數據後,如果因爲一些錯誤出現,我想填充我與以前的帖子數據形式...
反正我希望你們明白我想在這裏做,可以幫助我一點點:d
的簡單的解決方案是您應該在表單提交和處理後重定向用戶。
您可以檢查數據是否成功提交併處理重定向用戶,否則不重定向它們可以保留$_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
}
}
我只是想發佈這段代碼,它可以幫助遇到某種類型的情況時:
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
}
我不認爲這將看起來格式正確的評論,但我仍然想分享這個想法..
以及如果我想讓我的用戶保持在同一頁面?並沒有JavaScript或Ajax不是解決方案 – Linas
我想唯一的辦法是檢查如果表單submited,然後取消所有發佈數據,因爲我不想重定向用戶它會額外加載時間 – Linas
@Linas:不,在這樣您就無法阻止用戶使用瀏覽器刷新功能重新提交該數據。請注意,如果用戶刷新瀏覽器,則整個表單將被重新提交,即使您取消設置,$ _POST也會有數據。 –