2011-11-20 37 views
1

因此,标题说我想阻止用户继续向我的数据库提交$_POST数据。防止用户提交相同的发布数据

现在我已经是窗体数据提交到我的数据库的窗体和简单的类。问题是,如果用户提交数据并刷新浏览器,它会再次提交相同的数据。

我知道我可以刷新我的自我与元或页眉,但我不想做一些这么愚蠢的东西,所以我想我可以做一些像$_POST = null;不知道如果这样的作品,但我真的想要保持所有数据后,如果因为一些错误出现,我想填充我与以前的帖子数据形式...

反正我希望你们明白我想在这里做,可以帮助我一点点:d

回答

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 
    } 

} 
+0

以及如果我想让我的用户保持在同一页面?并没有JavaScript或Ajax不是解决方案 – Linas

+0

我想唯一的办法是检查如果表单submited,然后取消所有发布数据,因为我不想重定向用户它会额外加载时间 – Linas

+1

@Linas:不,在这样您就无法阻止用户使用浏览器刷新功能重新提交该数据。请注意,如果用户刷新浏览器,则整个表单将被重新提交,即使您取消设置,$ _POST也会有数据。 –

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 
} 

我不认为这将看起来格式正确的评论,但我仍然想分享这个想法..