菜鸡源码,专注精品下载!
当前位置:首页 > 建站教程 > 建站知识

防止PHP频繁刷新的方法

发布时间:2024-01-05  栏目:建站知识   浏览:   分类:php教程 php代码

PHP禁止频繁刷新的方法有很多,其中一种是使用session和cookie。首先,在需要登录的页面中设置一个session值,用于记录用户是否已经登录。然后,在每次用户访问该页面时,检查session值是否为空。如果为空,则跳转到登录页面;如果不为空,则允许用户访问该页面。此外,还可以使用cookie来记录用户的访问次数和时间间隔,以防止用户在短时间内频繁刷新页面。例如,可以设置一个名为“refresh”的cookie,用于记录用户的最后一次刷新时间。当用户再次访问该页面时,检查cookie中的刷新时间是否小于设定的时间间隔(如5秒),如果是,则不允许用户访问该页面。

PHP禁止同一IP频繁访问以防止网站被攻击或采集的代码,可以参考代码自己建立数据表文件,或不建立也可以使用,只是限制IP的功能就无法使用,但防止刷新可以继续使用。

header('Content-type:text/html;charset=utf-8');$ip=$_SERVER['REMOTE_ADDR'];//获取当前访问者的ip$logFilePath='./log/';//日志记录文件保存目录$fileht='.htaccess2';//被禁止的ip记录文件$allowtime=60;//防刷新时间$allownum=5;//防刷新次数$allowRefresh=120;//在允许刷新次数之后加入禁止ip文件中if(!file_exists($fileht)){file_put_contents($fileht,'');}$filehtarr=@file($fileht);if(in_array($ip."rn",$filehtarr)){exit('警告:你的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);}elseif($fileforbidarr[2]>$allowRefresh){file_put_contents($fileht,$ip."rn",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($ipdateas$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."rn";}elseif($numtem<$allownum){$str.=$iptem.$uritem.$timetem.($numtem+1)."rn";}else{if(!file_exists($fileforbid)){$addforbidarr=array($ip."rn",time()."rn",1);file_put_contents($fileforbid,$addforbidarr);}file_put_contents($logFilePath.'forbided_ip.log',$ip.'--'.date('Y-m-dH:i:s',time()).'--'.$uri."rn",FILE_APPEND);$timepass=$timetem+$allowtime-$time;exit('警告:不要刷新的太频繁!');}}}}if($yesno){$str.=$checkip.$checkuri.$time."rn";}file_put_contents($file,$str);


相关文章

    无相关信息
评论
建站知识
建站知识
使用技巧
调试安装
运营推广