08月18th

通过php获取访客真实ip并有效防cc的方法

DIY编程技术2666℃我来说两句!

我还是个小白,不喜莫喷。里面的防刷新时间和次数什么的请根据自己的需要修改。调用的方法是在需要防护的php里include就行了(建议header.php)。不懂include的自行百度。有问题请留言

<?phperror_reporting(0);$logFilePath='./log/';//日志记录文件保存目录$fileht='.htaccess2';//被禁止的ip记录文件$allowtime=60;//防刷新时间$allownum=5;//防刷新次数$allowRefresh=10;//在允许刷新次数之后加入禁止ip文件中    function getIp() {$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $list = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);$ip = $list[0]; } if (!ip2long($ip)) {$ip = '';} return $ip;}$ip=real_ip();if(!file_exists($fileht)){file_put_contents($fileht,'');}$filehtarr=file($fileht);if(in_array($ip."\r\n",$filehtarr)){exit('{"msg":"警告:你的IP已经被禁止了!"}');} //加入禁止ip$time=time();$fileforbid=$logFilePath.'forbidchk.dat';if(file_exists($fileforbid)){if($time-filemtime($fileforbid)>30){unlink($fileforbid);}else{$fileforbidarr=file($fileforbid);if($ip==substr($fileforbidarr[0],0,strlen($ip))){if($time-substr($fileforbidarr[1],0,strlen($time))>120){unlink($fileforbid);}else if($fileforbidarr[2]>$allowRefresh){file_put_contents($fileht,$ip."\r\n",FILE_APPEND);unlink($fileforbid);}else{$fileforbidarr[2]++;file_put_contents($fileforbid,$fileforbidarr);}}}}//防刷新$str='';$file=$logFilePath.'ipdate.dat';if(!file_exists($logFilePath)&&!is_dir($logFilePath)){mkdir($logFilePath,0777);}if(!file_exists($file)){file_put_contents($file,'');}$uri=$_SERVER['REQUEST_URI'];//获取当前访问的网页文件地址$checkip=md5($ip);$checkuri=md5($uri);$yesno=true;$ipdate=file($file);foreach($ipdate as $k=>$v){$iptem=substr($v,0,32);$uritem=substr($v,32,32);$timetem=substr($v,64,10);$numtem=substr($v,74);if($time-$timetem<$allowtime){if($iptem!=$checkip){$str.=$v;}else{$yesno=false;if($uritem!=$checkuri){$str.=$iptem.$checkuri.$time."\r\n";}else if($numtem<$allownum){$str.=$iptem.$uritem.$timetem.($numtem+1)."\r\n";}else{if(!file_exists($fileforbid)){$addforbidarr=array($ip."\r\n",time()."\r\n",1);file_put_contents($fileforbid,$addforbidarr);}file_put_contents($logFilePath.'forbided_ip.log',$ip.'--'.date('Y-m-d H:i:s',time()).'--'.$uri."\r\n",FILE_APPEND);$timepass=$timetem+$allowtime-$time;exit('{"msg":"警告:请不要频繁请求!"}');}}}}if($yesno){$str.=$checkip.$checkuri.$time."\r\n";}file_put_contents($file,$str);

本文出自:DIY博客园,链接:https://www.diybloghome.com/prology/1685.html,转载请注明!