Home >Backend Development >PHP Problem >How to ban ip from accessing website in php

How to ban ip from accessing website in php

藏色散人
藏色散人Original
2020-08-29 09:05:523841browse

php method to ban IP access to the website: first create a PHP sample file; then use "$ban_range_low" and "$ban_range_up" to ban a certain IP segment; finally output the IP access results.

How to ban ip from accessing website in php

Recommendation: "PHP Video Tutorial"

Example of PHP banning IP or IP address segment access

Example 1:

<? 
//禁止某个IP
$banned_ip = array (
"127.0.0.1",
"192.168.1.4"
);
if ( in_array( getenv("REMOTE_ADDR"), $banned_ip ) )
{
die ("您的IP禁止访问!");
}
//禁止某个IP段
$ban_range_low=ip2long("119.6.20.65");//IP段开始
$ban_range_up=ip2long("119.6.20.67");//IP段结束
$ip=ip2long($_SERVER["REMOTE_ADDR"]);
if ($ip>=$ban_range_low && $ip=<$ban_range_up)
{
echo "您的IP在被禁止的IP段之中,禁止访问!";
exit();
}
Echo “恭喜您的网络没有被屏蔽!”;
?>

Example 2:

Get restricted IP access records through text.

First create a given document such as blockip.txt

The content of the document is as follows (the specific blocked IP shall be modified in the following format):

BEGIN:
127.0.0.1
192.168.1.100

Prohibit single IP access:

<?php 
$ip=$_SERVER["REMOTE_ADDR"];
$ban=file_get_contents("blockip.txt");
if(stripos($ban,$ip))
{
  die("您的IP禁止访问!");  
}
echo "恭喜您的网络没有被屏蔽!";
?>

Block IP segment access:

<?php
$ip=$_SERVER["REMOTE_ADDR"];
while($ip[count($ip-1)]!=&#39;.&#39;)$ip=substr($ip,1, -1); //整理出ip段
$ban=file_get_contents("blockip.txt ");
if(stripos($ban,$ip))
{
  die("您的IP在被禁止的IP段之中,禁止访问!");  
}
echo "恭喜您的网络没有被屏蔽!";
?>

Note: You can add a page that restricts IP programs, such as blockip.php, and then use the include statement to reference the program code page in the relevant pages that need to restrict IP.

The above is the detailed content of How to ban ip from accessing website in php. For more information, please follow other related articles on the PHP Chinese website!

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