<?php<liu21st@gmail.com>
defined('THINK_PATH') or exit();
/**
* 系统行为扩展:表单令牌生成
* @category Think
* @package Think
* @subpackage Behavior
* @author liu21st <liu21st@gmail.com>
*/
class TokenBuildBehavior extends Behavior {
protected $options = array(
'TOKEN_ON' => false, 'TOKEN_NAME' => '__hash__', 'TOKEN_TYPE' => 'md5', 'TOKEN_RESET' => true, );
public function run(&$content){
if(C('TOKEN_ON')) {
if(strpos($content,'{__TOKEN__}')) {
$content = str_replace('{__TOKEN__}',$this->buildToken(),$content);
}elseif(preg_match('/<\/form(\s*)>/is',$content,$match)) {
$content = str_replace($match[0],$this->buildToken().$match[0],$content);
}
}else{
$content = str_replace('{__TOKEN__}','',$content);
}
}
private function buildToken() {
$tokenName = C('TOKEN_NAME');
$tokenType = C('TOKEN_TYPE');
if(!isset($_SESSION[$tokenName])) {
$_SESSION[$tokenName] = array();
}
$tokenKey = md5($_SERVER['REQUEST_URI']);
if(isset($_SESSION[$tokenName][$tokenKey])) $tokenValue = $_SESSION[$tokenName][$tokenKey];
}else{
$tokenValue = $tokenType(microtime(TRUE));
$_SESSION[$tokenName][$tokenKey] = $tokenValue;
}
$token = '<input type="hidden" name="'.$tokenName.'" value="'.$tokenKey.'_'.$tokenValue.'" />';
return $token;
}
}