Home >Backend Development >PHP Problem >How to ban ip from accessing website in php
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.
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)]!='.')$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!