我有一个向SQL表提交文本的简单表单。问题在于,在用户提交文本之后,他们可以刷新页面并再次提交数据,而无需再次填写表单。我可以在文本提交后将用户重定向到另一个页面,但我希望用户停留在同一页面上。

我记得我读过一些关于给每个用户一个唯一的会话id,并将其与另一个值进行比较,这解决了我所遇到的问题,但我忘记了它在哪里。


当前回答

我使用这个javascript行来阻止弹出窗口要求表单重新提交刷新一旦表单提交。

if ( window.history.replaceState ) {
  window.history.replaceState( null, null, window.location.href );
}

只需将这一行放在文件的页脚,就能看到神奇的效果

其他回答

一个非常可靠的方法是在post中实现一个唯一的ID,并将其缓存到

<input type='hidden' name='post_id' value='".createPassword(64)."'>

然后在你的代码中这样做:

if( ($_SESSION['post_id'] != $_POST['post_id']) )
{
    $_SESSION['post_id'] = $_POST['post_id'];
    //do post stuff
} else {
    //normal display
}

function createPassword($length)
{
    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
    srand((double)microtime()*1000000);
    $i = 0;
    $pass = '' ;

    while ($i <= ($length - 1)) {
        $num = rand() % 33;
        $tmp = substr($chars, $num, 1);
        $pass = $pass . $tmp;
        $i++;
    }
    return $pass;
}

处理表单时,重定向到另一个页面:

... process complete....
header('Location: thankyou.php');

您也可以重定向到同一页面。

如果您正在做一些类似评论的事情,并且希望用户停留在相同的页面上,您可以使用Ajax来处理表单提交

使用Post/Redirect/Get模式。http://en.wikipedia.org/wiki/Post/Redirect/Get

对于我的网站,我将在cookie或会话中存储消息,在发布后重定向,读取cookie/会话,然后清除该会话或cookie变量的值。

这个form.php示例展示了如何正确地使用PRG(当表单有效或无效时)。

它只在表单有效且执行操作时重定向到相同的页面。 重定向可以防止表单在页面刷新时被重新提交。 当表单有效时,它使用session来避免丢失想要显示的成功消息。 有两个测试按钮:“有效提交”,“无效提交”。两者都试一下,然后刷新页面。

<?php
session_start();

function doSelfRedirect()
{
  header('Location:'.$_SERVER['PHP_SELF']);
  exit;
}

function setFlashMessage($msg)
{
  $_SESSION['message'] = $msg;
}

function getFlashMessage()
{
  if (!empty($_SESSION['message'])) {
    $msg = $_SESSION['message'];
    unset($_SESSION['message']);
  } else {
    $msg = null;
  }

  return $msg;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // Validation primitive example.
  if (empty($_POST['valid'])) {
    $formIsValid = false;
    setFlashMessage('Invalid form submit');
  } else {
    $formIsValid = true;
  }

  if ($formIsValid) {
    // Perform any actions here.
    // ...

    // Cool!
    setFlashMessage('Form is valid. Action performed.');

    // Prevent form resubmission.
    doSelfRedirect();
  }
}
?>
<h1>Hello form</h1>

<?php if ($msg = getFlashMessage()): ?>
  <div><?= $msg ?></div>
<?php endif; ?>

<form method="post">
  <input type="text" name="foo" value="bar"><br><br>
  <button type="submit" name="invalid" value="0">Invalid submit</button>
  <button type="submit" name="valid" value="1">Valid submit</button>
</form>

你真的应该使用Post Redirect Get模式来处理这个问题,但如果你在某种程度上陷入了PRG不可行的境地(例如,表单本身在一个include中,防止重定向),你可以散列一些请求参数,根据内容生成一个字符串,然后检查你是否已经发送了它。

//create digest of the form submission:

    $messageIdent = md5($_POST['name'] . $_POST['email'] . $_POST['phone'] . $_POST['comment']);

//and check it against the stored value:

    $sessionMessageIdent = isset($_SESSION['messageIdent'])?$_SESSION['messageIdent']:'';

    if($messageIdent!=$sessionMessageIdent){//if its different:          
        //save the session var:
            $_SESSION['messageIdent'] = $messageIdent;
        //and...
            do_your_thang();
    } else {
        //you've sent this already!
    }