|
學(xué)校的新聞系統(tǒng)要求有些新聞只開(kāi)放校內(nèi)ip瀏覽,于是重寫(xiě)了一個(gè)代碼來(lái)實(shí)現(xiàn)此功能,實(shí)現(xiàn)后的結(jié)果是,只要把允許訪問(wèn)的ip列入ip.txt這個(gè)文件中即可,同時(shí)支持c類ip,例如:
ip.txt
192.168
211.67.188
211.67.191.25
代碼如下:
復(fù)制代碼 代碼如下:
/*
* ip地址黑名單、白名單
* 判斷訪客地址的ip是否在ip.txt中,支持c類ip
* By xhat
*/
$ip = $_SERVER['REMOTE_ADDR'];
$ipArray = preg_replace("#rn?|n#","",file('ip.txt'));
foreach ($ipArray as $ipTest) {
if (substr_count($ip, $ipTest) != "0") {
echo "ok"; //執(zhí)行相關(guān)命令
die();
}
}
?>
上面大家可以使用代碼來(lái)騙過(guò)了,下面代碼進(jìn)行升級(jí)
復(fù)制代碼 代碼如下:
<?php
class block_ip {
var $Block_ip = array("192.168.1.1","210.10.2.1-20","222.34.4.*");
function __construct(){
}
function __destruct(){
}
private function makePregIP($str){
if (strstr($str,"-")) {
$aIP = explode(".",$str);
foreach ($aIP as $k=>$v) {
if (!strstr($v,"-")) {
$preg_limit .= makePregIP($v);
} else{
$aipNum = explode("-",$v);
for($i=$aipNum[0];$i<=$aipNum[1];$i++){
$preg .=$preg?"|".$i:"[".$i;
}
$preg_limit .=strrpos($preg_limit,".",1)==(strlen($preg_limit)-1)?$preg."]":".".$preg."]";
}
}
}else{
$preg_limit .= $str.".";
}
return $preg_limit;
}
private function getAllBlockIP(){
if ($this->Block_ip) {
foreach ($this->Block_ip as $k=>$v) {
$ipaddres = $this->makePregIP($v->start_ip);
$ip = str_ireplace(".",".",$ipaddres);
$ip = str_replace("*","[0-9]{1,3}",$ip);
$ipaddres = "/".$ip."/";
$ip_list[] = $ipaddres;
}
}
return $ip_list;
}
public function checkIP() {
$iptable = $this->getAllBlockIP();
$IsJoined = true;
//取得用戶ip
$Ip = $this->get_client_ip();
$Ip = trim($Ip);
//剔除黑名單中的IP區(qū)段
if ($iptable) {
foreach($iptable as $value) {
if (preg_match("{$value}",$Ip)) {
$IsJoined = false;
break;
}
}
}
// 如果在ip黑名單中就執(zhí)行如下操作
if( !$IsJoined ){
echo "IP Error";
exit;
}
}
private function get_client_ip(){
if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
$ip = getenv("HTTP_CLIENT_IP");
else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
$ip = getenv("HTTP_X_FORWARDED_FOR");
else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
$ip = getenv("REMOTE_ADDR");
else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
$ip = $_SERVER['REMOTE_ADDR'];
else
$ip = "unknown";
return($ip);
}
}
?>
引用片段:
復(fù)制代碼 代碼如下:
$oBlock_ip = new block_ip();
$oBlock_ip->checkIP();
php技術(shù):php判斷ip黑名單程序代碼實(shí)例,轉(zhuǎn)載需保留來(lái)源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。