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

<?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>

posted @ 2013-07-31 14:24  幻星宇  阅读(334)  评论(0编辑  收藏  举报