简体   繁体   English

在用户刷新网页时阻止表单提交

[英]Prevent form submitting when user refreshes webpage

I have a simple counter for the form button clicks which works well but when the user refreshes the page it adds onto the counter again. 对于表单按钮单击,我有一个简单的计数器,效果很好,但是当用户刷新页面时,它将再次添加到计数器中。 I would be grateful if someone would help with the coding I have wrote below. 如果有人可以帮助我编写下面的代码,我将不胜感激。

PHP CODE PHP代码

<?php
if( isset($_POST['clicks']) ) { 
    incrementClickCount();
}

function getClickCount()
{
    return (int)file_get_contents("clickcount.txt");
}

function incrementClickCount()
{
    $count = getClickCount() + 1;
    file_put_contents("clickcount.txt", $count);
}
?>

HTML and PHP FORM CODE HTML和PHP表单代码

<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
            <input type="submit" value="click me!" name="clicks">
        </form> <div>Click Count: <?php echo getClickCount(); ?></div>

为了防止这种情况,您需要实现POST / REDIRECT / GET模式

Just redirect the request to the same page after processing the form post. 处理表单后,只需将请求重定向到同一页面即可。 This can be done as follows in PHP: 可以在PHP中按以下步骤完成:

<?php header('Location: http://www.example.com/'); ?>

If the user refreshes (after this redirect) nothing would be resubmitted. 如果用户刷新(在此重定向之后),则不会重新提交任何内容。

Afroze has a good point. 非洲人有一个好点。 Using a header refresh will reset all form data, but it forces the page to refresh twice (when the form is first submitted, and second time when the header forces another refresh). 使用标头刷新将重置所有表单数据,但是它将强制页面刷新两次(第一次提交表单时,第二次刷新标头时再次刷新)。 There is another method of preventing a "refresh submission" without forcing a second refresh. 还有另一种防止“刷新提交”而不强制第二次刷新的方法。

Try this (I'll explain the code below): 试试看(我将在下面解释代码):

<?php
    //begin a session
    session_start();

    //generate a MD5 hash from concatenated form $_POST values
    $formDataHash = md5($_POST['clicks'] . $_POST['otherFormContent']);


    //if form has been submitted before, and the data passed from the form
    //is the same as the previous submission, return false (don't do anything)

    if(isset($_SESSION['formData']) && $_SESSION['formData'] == $formDataHash)
    {
        return false;
    }
    else
    {
        //increase click count
        incrementClickCount();

        //store the submission values
        $_SESSION['formData'] = $formDataHash;
    }

The code above will detect a each form submission, but won't process duplicates. 上面的代码将检测每个表单提交,但不会处理重复的表单。 It also won't refresh the page twice (which isn't ideal for users with slow connections). 它也不会刷新页面两次(这对于连接速度慢的用户而言并不理想)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM