Home  >  Article  >  Backend Development  >  PHP implementation code that prohibits access to a single IP address or IP segment

PHP implementation code that prohibits access to a single IP address or IP segment

WBOY
WBOYOriginal
2016-07-25 09:00:281064browse
How does the PHP code disable access to a single IP or IP segment? We provide you with two reference codes. Friends who are interested can take a look.

1. Forbid single IP access

<?php
//加IP访问限制
//搜集整理 程序员之家 bbs.it-home.org
if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
$userip = getenv('HTTP_CLIENT_IP');
} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
$userip = getenv('HTTP_X_FORWARDED_FOR');
} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
$userip = getenv('REMOTE_ADDR');
} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
$userip = $_SERVER['REMOTE_ADDR'];
}
$banned_ip = array (
"127.0.0.1",
"203.0.0.1",
"56.12.50.65",
"192.168.1.88"
);
if (in_array($userip,$banned_ip))
{
   die ("对不起,您的IP被禁止访问!");
}
   echo "您可以正常访问,马上为您跳转!";
?>

Now that we have talked about how to ban IP address access, mastering how to obtain a real IP address has become a basic skill that must be strengthened. Friends who are interested can refer to the following articles: Two ways to get the real IP of the external network with php php code to obtain client IP address, geographical information, browser information, and local real IP php code to get accurate client IP address How to implement filtering IP black and white lists in php Multiple ways to get IP with php How to get visitor IP with php 2. Prohibit IP segment access

<?php
//加IP访问限制
//by 程序员之家 http://bbs.it-home.org
if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
$userip = getenv('HTTP_CLIENT_IP');
} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
$userip = getenv('HTTP_X_FORWARDED_FOR');
} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
$userip = getenv('REMOTE_ADDR');
} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
$userip = $_SERVER['REMOTE_ADDR'];
}
$ban_range_low=ip2long("217.0.0.0"); //ip段上
$ban_range_up=ip2long("217.255.255.255");//ip段尾
$ip=ip2long($userip]);
if ($ip>$ban_range_low && $ip<$ban_range_up)
{
print "Banned";
exit();
}
?> 
Articles you may be interested in: PHP example code for banning IP access to the website php function to ban ip access


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn