1.请求时把生成的随机数传入表单并存入session:
$formHash = Tools::getHashStr(6);
$session['formHash'] = $formHash;
2.from表单
<input type="hidden" value="<?php echo $formHash; ?>" name="formHash" />
3.提交表单后判断,如果不等直接跳回,否则提交成功
if($formHash == $session['formHash']) {
unset($session['formHash']);
}
4.获取随机数方法getHashStr()
/**
* 生成随机字符串
*/
public static function getHashStr($length = 6) {
$strArr = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y','z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L','M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y','Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
$keys = array_rand($strArr, $length);
$randStr = '';
if(!empty($keys)) {
foreach ($keys as $k => $value) {
$randStr .= $strArr[$value];
}
}
return $randStr;
}