PHP服务器端防止用户重复提交数据
<?php
session_start();
/**
* 检查表单是否被重复提交
* 相同内容的表单在设定时间内只能提交1次
* @param int $iTimeOffset
* @return bool
*/
function checkFormSubmit($iTimeOffset=60){
// 取得表单的标识
$idForm = md5(serialize($_POST));
// 是否需要表单提交检察
$iFormCheck = true;
if (isset($_SESSION['formSubmitCheck'])){
// 删除过期的表单标识
foreach (array_keys($_SESSION['formSubmitCheck']) as $val){
if (time() > $val){
unset($_SESSION['formSubmitCheck'][$val]);
}
}
}else {
$_SESSION['formSubmitCheck'] = array();
$iFormCheck = false;
}
if ($iFormCheck == true){
// 检查是否有重复标识的提交记录
foreach ($_SESSION['formSubmitCheck'] as $val){
if ($val == $idForm){
return false;
}
}
}
// 保存表单标识
$_SESSION['formSubmitCheck'][(time()+$iTimeOffset)] = $idForm;
return true;
}
if (count($_POST) > 0){
if (checkFormSubmit()===true){
echo '表单提交成功';
}else {
echo '表单重复提交';
}
}
?>
<form method="POST">
<input type="text" name="a">
<input type="text" name="b">
<textarea name="c"></textarea>
<input type="submit" name="btnSubmit" value="确认">
</form>
<?php
var_dump($_POST);
var_dump($_SESSION);
?>
session_start();
/**
* 检查表单是否被重复提交
* 相同内容的表单在设定时间内只能提交1次
* @param int $iTimeOffset
* @return bool
*/
function checkFormSubmit($iTimeOffset=60){
// 取得表单的标识
$idForm = md5(serialize($_POST));
// 是否需要表单提交检察
$iFormCheck = true;
if (isset($_SESSION['formSubmitCheck'])){
// 删除过期的表单标识
foreach (array_keys($_SESSION['formSubmitCheck']) as $val){
if (time() > $val){
unset($_SESSION['formSubmitCheck'][$val]);
}
}
}else {
$_SESSION['formSubmitCheck'] = array();
$iFormCheck = false;
}
if ($iFormCheck == true){
// 检查是否有重复标识的提交记录
foreach ($_SESSION['formSubmitCheck'] as $val){
if ($val == $idForm){
return false;
}
}
}
// 保存表单标识
$_SESSION['formSubmitCheck'][(time()+$iTimeOffset)] = $idForm;
return true;
}
if (count($_POST) > 0){
if (checkFormSubmit()===true){
echo '表单提交成功';
}else {
echo '表单重复提交';
}
}
?>
<form method="POST">
<input type="text" name="a">
<input type="text" name="b">
<textarea name="c"></textarea>
<input type="submit" name="btnSubmit" value="确认">
</form>
<?php
var_dump($_POST);
var_dump($_SESSION);
?>