Php Security development adds random string verification to prevent forgery of cross-site requests. Yahoo's solution to counterfeit cross-site requests is to add a random string named. crumb to the form. facebook also has a similar solution, in which there are usually post_form_id and fb_dtsg. Yahoo's solution to counterfeit cross-site requests is to add a random string named. crumb to the form. facebook also has a similar solution, in which there are usually post_form_id and fb_dtsg.
A common and inexpensive precaution is to add a random and frequently changed string to all forms that may involve user write operations, then, check the string when processing the form. If this random string is associated with the current user identity, it will be troublesome for attackers to forge requests. Currently, the defense methods are basically based on this method.
Random string code implementation
We follow this idea to implement a crumb. the code is as follows:
The code is as follows:
Class Crumb {
Const salt = "your-secret-salt ";
Static $ ttl = 7200;
Static public function challenge ($ data ){
Return hash_hmac ('md5', $ data, self: SALT );
}
Static public function issueCrumb ($ uid, $ action =-1 ){
$ I = ceil (time ()/self: $ ttl );
Return substr (self: challenge ($ I. $ action. $ uid),-12, 10 );
}
Static public function verifyCrumb ($ uid, $ crumb, $ action =-1 ){
$ I = ceil (time ()/self: $ ttl );
If (substr (self: challenge ($ I. $ action. $ uid),-12, 10) = $ crumb |
Substr (self: challenge ($ I-1). $ action. $ uid),-12, 10) ==$ crumb)
Return true;
Return false;
}
}
In the code, $ uid indicates the unique identifier of the user, and $ ttl indicates the validity period of the random string.
Application example
Construct a form
Insert a hidden random string crumb into the form.
The code is as follows:
Process form demo. php
Check crumb
The code is as follows:
If (Crumb: verifyCrumb ($ uid, $ _ POST ['Crumb']) {
// Process the form according to the normal process
} Else {
// Crumb verification failed, error prompt process
}
This article is from baozi blog
....