最近研究个人博客,防止外部攻击,可以通过限制ip的方式实现一定的防护。
防止自己的ip一直变,可以去花生壳申请一个DDNS,这样就能动态判断了!
这里做了4次限制,如果不想花里胡哨的,检测到IP不对直接exit就行了。
直接上源码:
<?php
class checkClass{
function checkUserIp() {
$IP = isset( $_SERVER['HTTP_X_FORWARDED_FOR'] )?$_SERVER['HTTP_X_FORWARDED_FOR']
:( isset( $_SERVER['HTTP_CLIENT_IP'] )?$_SERVER['HTTP_CLIENT_IP']
:$_SERVER['REMOTE_ADDR'] );
$officeIp = gethostbyname( 'office.xxx.xxx' );//
if ( $IP != $officeIp ) {
define( 'count_num', '4' ); //访问最大次数
define( 'count_time', '3600' ); //访问最大时间
session_start();
//开启session
$now_time = time();
//判断session存在,赋值
if ( $_SESSION ) {
$last_time = $_SESSION['last_time'];
$times = $_SESSION['times'] + 1;
$_SESSION['times'] = $times;
} else {
$last_time = $now_time;
$times = 1;
$_SESSION['times'] = $times;
$_SESSION['last_time'] = $last_time;
}
//开始时间判断,如果超过时间次数,则退出程序
if ( ( $now_time - $last_time ) < count_time ) {
if ( $times >= count_num ) {
exit;
} else {
header( 'HTTP/1.1 403 Forbidden' );
die;
}
} else {
$times = 0;
$_SESSION['last_time'] = $now_time;
$_SESSION['times'] = $times;
}
}
}
}