This function is used to count how many times each visitor has visited in a short period of time, and returns true if the number of times limit is exceeded, after which you can use PHP to call Linux iptables for blocking operations. I've used several DDoS-like tools to actually test it, and it works really well. By the way, I use files in the code to record the visitor's IP and time, it is best not using the database (nor smart to save the session), it is also best to put this file into the SSD hard disk, the reason why I don't say, I guess everyone knows
- /**
- Prevent customer-side evil reorganization
- Usage:
- $ISF 5=fun::isf5 ();
- Return:
- Return to Bool[true: The opposite party is in a wicked reorganization; false: Normal interview]
- /**/
- public static function Isf5 () {
- $_f=run. ' _isf5 ';
- if (!file_exists ($_f)) {
- File_put_contents ($_f,serialize (Array ()), LOCK_EX);
- chmod ($_f,0777);
- }
- $arr =unserialize (file_get_contents ($_f));
- $arr = (!is_array ($arr))? Array (): $arr;
- Clean up the user who was interviewed 10 seconds ago
- foreach ($arr as $k = = $v) {
- if ($_env[' now ']-$v [' t '] >= 10) {
- Unset ($arr [$k]);
- }
- }
- $ip = ' _ '. (Self::cur (' IP '));
- if (!isset ($arr [$ip])) {
- $arr [$ip] [' N ']=1;//1s
- $arr [$ip] [t ']=$_env[' now '];//the 1th time
- File_put_contents ($_f,serialize ($arr), LOCK_EX);
- chmod ($_f,0777);
- Unset ($_f, $arr, $IP);
- return FALSE;
- }else{
- if (!isset ($arr [$ip] [' t ']) or!is_numeric ($arr [$ip] [' t '])) {
- Unset ($arr [$ip]);
- File_put_contents ($_f,serialize ($arr), LOCK_EX);
- chmod ($_f,0777);
- Unset ($_f, $arr, $IP);
- return FALSE;
- }
- if ($_env[' now ')-$arr [$ip [' t ']) <= 1) {//If the distance from the last interview is not over 1s, it only accumulates the number of times
- $arr [$ip] [' N ']+=1;
- if ($arr [$ip] [' n ']>=5) {
- Unset ($_f, $arr, $IP);
- return TRUE;
- }else{
- File_put_contents ($_f,serialize ($arr), LOCK_EX);
- chmod ($_f,0777);
- Unset ($_f, $arr, $IP);
- return FALSE;
- }
- }else{//if the distance from the last visit has been over 1s, then re-calculate
- $arr [$ip] [' N ']=1;
- $arr [$ip] [' t ']=$_env[' now '];
- File_put_contents ($_f,serialize ($arr), LOCK_EX);
- chmod ($_f,0777);
- Unset ($_f, $arr, $IP);
- return FALSE;
- }
- }
- Unset ($_f, $arr, $IP);
- return FALSE;
- }
Copy Code |