/**
* Principle: When requesting to allocate a token, find a way to allocate a unique token, base64( time + rand + action)
* If submitted, record this token to indicate that this token has been used and can be used accordingly It is used to avoid duplicate submissions.
*
*/
class GToken {
/**
* Get all current tokens
*
* @return array
*/
public static function getTokens(){
$tokens = $_SESSION[GConfig::SESSION_KEY_TOKEN ];
if (empty($tokens) && !is_array($tokens)) {
$tokens = array();
}
return $tokens;
}
/**
* Generate a new Token
*
* @param string $formName
* @param Encryption key $key
* @return string
*/
public static function granteToken($formName,$key = GConfig::ENCRYPT_KEY ){
$token = GEncrypt::encrypt($formName.":".session_id(),$key);
return $token;
}
/**
* Deleting a token actually adds an element to an array in the session, indicating that the token has been used before to avoid repeated submission of data.
*
* @param string $token
*/
public static function dropToken($token){
$tokens = self::getTokens();
$tokens[] = $token;
GSession::set(GConfig::SESSION_KEY_TOKEN ,$tokens);
}
/**
* Check whether it is the specified Token , if true, it will be judged whether the session_id attached to the token is the same as the current session_id.
* @param string $key encryption key
* @return boolean
*/
public static function isToken($token,$formName,$fromCheck = false,$key = GConfig::ENCRYPT_KEY){
$tokens = self::getTokens();
if (in_array($token,$tokens)) //如果存在,说明是以使用过的token
return false;
$source = split(":", GEncrypt::decrypt($token,$key));
if($fromCheck)
return $source[1] == session_id() && $source[0] == $formName;
else
return $source[0] == $formName;
}
}
?>
Example:
First take out the token from $_POST and use isToken to judge.
Downloading this file seems to be no problem.
If you want to judge whether it is To execute the matching action, you can change the formName in isToken and run it. It works fine. There is no match. This proves that this is successful.
I have not verified whether repeated submissions can be avoided. It is too simple logic.
The rest is to determine whether the source check is working properly.
Copy the html generated by the above example to a local web page (to achieve the purpose of different domains), run it, and check for unknown sources , no action is executed (you need to set the third parameter of isToken to true).
Set the third parameter of isToken to false, submit, and the specified action is executed!
Okay, here we go So far, I don’t know if there are still BUGs in any places. This will need to be debugged and modified slowly in long-term use!
http://www.bkjia.com/PHPjc/318686.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/318686.htmlTechArticleHow to achieve the goal: How to avoid repeated submissions? An array must be stored in the SESSION, which stores the successfully submitted token. During background processing, first determine whether the token is in this array...