PHP prevents cross-site form submission and cross-site form forgery attacks
In the previous defense against cross-site attacks, we used to verify whether the submitted page is the same site, which can prevent normal attacks. ereg ("www.rczjp.com ", $ _ SERVER ['HTTP _ referer'])
However, it is not very secure because attackers can forge HTTP Referer, such as header ("Referer: www.rczjp.cn") or forge HTTP headers in malicious scripts.
Because HTTP Referer is sent by the client browser rather than controlled by the server, you should not use this variable as a trust source.
Of course, the verification code can be used for logon, but many other forms are not suitable for submission.
The following provides a solution to prevent the submission of forged forms, and solves illegal calls to different pages of the same site!
// --------------- Code -------------//
Session_start ();
# Random 6-bit Hash Value
Function gen_token (){
$ Hash = md5 (uniqid (rand (), true ));
$ N = rand (1, 26 );
$ Token = substr ($ hash, $ n, 6 );
Return $ token;
}
Function ck_form (){
If (_ POST ('qm _ token') = ''| _ SESSION ('Token') ='' | _ POST ('qm _ token ')! = _ SESSION ('Token ')){
Exit ('Do not submit illegally ');
}
}
Function token_input (){
$ Token = gen_token ();
$ _ SESSION ['Token'] = $ token;
Echo "<input type = 'den den 'name = 'qm _ token' value =' $ token'/> ";
}
// Usage method, pay attention to the order
If (_ POST ('add ')! = ''){
# Verify the validity of the submitted page when submitting the form
Ck_form ();
Normal www.2cto.com CODE...
}
<Form name = "form1" action = "" method = "post">
<? Php token_input ();?>
Other HTML...
</Form>
// ------------ Code ended -------------//
Principle: When a form is submitted illegally across different pages or on the same site
The hidden domain and SESSION value obtained during the cross-site operation are empty. It can be determined that the request is submitted illegally because the SESSION and hidden domain on the Legal page are assigned the same hash value.
The SESSION value of the same site is not the same as the value of the hidden domain obtained by POST, so it can be determined that the request is submitted illegally.
NOTE:
Function _ POST ($ str ){
$ Val =! Empty ($ _ POST [$ str])? $ _ POST [$ str]: null;
Return $ val;
}
Function _ GET ($ str ){
$ Val =! Empty ($ _ GET [$ str])? $ _ GET [$ str]: null;
Return $ val;
}
Function _ SESSION ($ str ){
$ Val =! Empty ($ _ SESSION [$ str])? $ _ SESSION [$ str]: null;
Return $ val;
}