如何防止我的PHP表单在刷新时重新提交

时间:2015-09-16 09:10:58

标签: javascript php forms oracle

我使用以下代码在数据库中提交字段(使用oracle),但在成功提交表单后,如果我刷新表单,表单将被重新提交。我这里没有使用任何会话。

请帮忙

<div class="col-xs-5">
    <?php
    $note=$_REQUEST['note'];
    $order = "INSERT INTO ec_note (nid, idno, note, flag, ec_date)
            VALUES
            (a_seq.nextval,'$id',
            '$note',1,sysdate)";
        if ($note)
        {
        $result = dbi_query($conn, $order); //order executes
        }
        if($result){
            echo("<div class='alert alert-success alert-dismissible' role='alert'>Your Note has been successfully uploaded
            <button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button>
            </div>");
            }

    ?>
    <form method="post" action="">
        <textarea class="form-control" name="note" rows="15" placeholder="Maximum 4000 characters "></textarea> <br>
        <button type="submit" name="submit" onSubmit="window.location.reload()" class="btn btn-primary btn-lg btn-block">Add Note</button>
    </form>
</div>

1 个答案:

答案 0 :(得分:1)

像这样提交表格:

<form method="post" action="">
    <textarea class="form-control" name="note" rows="15" placeholder="Maximum 4000 characters "></textarea> <br>
    <button type="submit" name="confirm" class="btn btn-primary btn-lg btn-block">Add Note</button>
</form>

现在的问题是,如果您重新加载刚刚发布的页面,POST将重复。然后,您需要这种页面执行重新加载。要执行此操作,您需要POSTed页面永远不会在浏览器中显示

  • 你打开页面(这是一个GET)
  • 页面显示但未自动发布
  • 您提交了该页面(这是一个POST)
  • 通过GET &lt; -
  • 再次获取该页面
  • 页面显示但未自动发布
  • (重复)

您可以通过检查是否有请求来实现此目的,如果是,则在执行数据库插入后,您将重定向到同一页而不使用POST 。除非使用缓冲,否则必须在将任何输出发送到浏览器之前完成此操作:

$note=$_REQUEST['note'];
$order = "INSERT INTO ec_note (nid, idno, note, flag, ec_date)
    VALUES
    (a_seq.nextval,'$id',
    '$note',1,sysdate)";
if ($note)
{
    $result = dbi_query($conn, $order); //order executes, allowing SQL injection.
    // This reloads without allowing resubmit, unless button is pressed again
    // No other output must have been sent, or this WILL cause an error.
    die(Header("Location: {$_SERVER['PHP_SELF']}"));
}

重要即可。你相信&#34;注意&#34;字段通过POST到达并且不包含任何不良内容。 情况可能并非总是如此

因此要么使用带有准备值的查询,要么使用转义来阻止来自summoning the dreaded Bobby Tables$_REQUEST['note']

更好的实施:

if (isset($_POST)
    && array_key_exists('note', $_POST)
) {
    // I am not familiar with dbi_query. I suppose there exists a dbi_escape function?
    $note = YOUR_ESCAPE_FUNCTION($_POST['note'];)
    $order = "INSERT INTO ec_note (nid, idno, note, flag, ec_date)
    VALUES
    (a_seq.nextval,'$id',
    '$note',1,sysdate)";
    $result = dbi_query($conn, $order);

    // CHECK ERRORS AND DISPLAY THE APPROPRIATE RESPONSE

    // If no error, reload the form with a redirect and quit.
    // No output must have been sent to the browser up to now, or
    // this will cause an error.
    die(Header("Location: {$_SERVER['PHP_SELF']}"));
}