我有一个简单的表格按钮点击计数器,但效果很好但是当用户刷新页面时,它会再次添加到计数器上。如果有人帮我处理下面编写的代码,我将不胜感激。
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和PHP FORM CODE
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<input type="submit" value="click me!" name="clicks">
</form> <div>Click Count: <?php echo getClickCount(); ?></div>
答案 0 :(得分:3)
为防止这种情况,您需要实施POST/REDIRECT/GET pattern。
答案 1 :(得分:0)
在处理表单后,只需将请求重定向到同一页面。这可以在PHP中完成如下:
<?php header('Location: http://www.example.com/'); ?>
如果用户刷新(在此重定向之后),则不会重新提交任何内容。
答案 2 :(得分:0)
Afroze有一个好点。使用标题刷新将重置所有表单数据,但它会强制页面刷新两次(首次提交表单时,以及标题强制另一次刷新时第二次)。还有另一种方法可以在不强制第二次刷新的情况下阻止“刷新提交”。
试试这个(我将解释下面的代码):
<?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;
}
上面的代码将检测每个表单提交,但不会处理重复项。它也不会刷新页面两次(这对于连接速度慢的用户来说并不理想。)