Php code for restricting access from a single IP address and ip address segment
I will share two pieces of php code that limits IP address access. There are two examples of code: restrict access from a single IP address and restrict access from an IP address segment. For more information, see.
-
- // Add IP address access restrictions
- 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 ("Your IP is block to connect! ");
- }
- Echo "test code! Test ";
- ?>
Example 2: IP segment restriction: restrict IP segment access.
-
- // Add IP address access restrictions
- 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"); // on the ip address segment
- $ Ban_range_up = ip2long ("217.00000000255"); // ip end
- $ Ip = ip2long ($ userip]);
- If ($ ip> $ ban_range_low & $ ip <$ ban_range_up)
- {
- Print "Banned ";
- Exit ();
- }
- ?>
|