PHP简单利用token防止表单重复提交(转)

时间:2023-03-08 17:22:09

<?php
/*
* PHP简单利用token防止表单重复提交
*/
function set_token() {
$_SESSION['token'] = md5(microtime(true));
}

function valid_token() {
$return = $_REQUEST['token'] === $_SESSION['token'] ? true : false;
set_token(); //重新设置token
return $return;
}

//如果token为空则生成一个token
if (!isset($_SESSION['token']) || $_SESSION['token'] == '') {
set_token();
}

if (isset($_POST['test'])) {
if (!valid_token()) {
echo 'token error';
} else {
echo time();
}
}
?>
<form method="post" action = "">
<input type="hidden" name="token" value="<?php echo $_SESSION['token']; ?>" />
<input type="text" name="test" value="good" />
<input type="submit" />
</form>