index.php ```php ``` index_do.php ```php ``` CsrfTokenClass.php ```php '校验出错'); echo json_encode($aRtn); die(); } } /** * 校验token值 -- ajax校验 * @param unknown $postToken */ public static function ajaxGate($postToken) { $csrfId = self::getCsrfID(); $token = self::getCsrfKey($csrfId, $postToken); //查询db是否存在 if (!self::getToken($token)) { header("HTTP/1.1 403 Forbidden"); $aRtn = array('error'=>'校验出错'); echo json_encode($aRtn); die(); } } /** * 校验token值 -- 直接返回 * @param string $postToken * @return boolean */ public static function isValid($postToken) { $csrfId = self::getCsrfID(); $token = self::getCsrfKey($csrfId, $postToken); return self::getToken($token); } private static function getCsrfKey($csrfId, $csrfToken) { return md5('csrfid:' . $csrfId . ':' . $csrfToken); } private static function saveToken($token) { if(empty($token)) { return false; } return self::addCsrfToken($token); } private static function getToken($token) { if(empty($token)) { return false; } return self::getCsrfToken($token); } private static function addCsrfToken($token) { $sQuery = 'INSERT INTO csrf_log SET token = "' . addslashes($token) . '", date_create = NOW()'; return $oDB->exec($sQuery); } private static function getCsrfToken($token) { $sQuery = 'SELECT * FROM csrf_log WHERE token = "' . addslashes($token) . '" AND DATE_FORMAT(ADDDATE(`date_create`, INTERVAL '.self::EXPIRTIME.' MINUTE), "%Y-%m-%d %H:%i:%s") >= NOW()'; return $oDB->getRow($sQuery); } } ```