There are many reasons you may need to block an IP address from
visiting your website. For example, to prevent particular users doing
malicious things with your website – trying to spam your web forms, or
hack your shopping cart, etc. Using PHP, you can easily find your site
visitors’ website addresses and based on these addresses to redirect
them to specific places on your site. If you use such IP ban protection
on your website, you will also need to not only list individual
addresses to be blocked but also IP masks and IP ranges.
Let’s start! First, we will create an array to list all the IP addresses that we want to block. Besides single IP addresses, we will also use IP ranges such as 184.108.40.206-220.127.116.11 and IP masks 100.88.*.*. Here is the array
When a visitor comes to your website you will need to find their IP
address and store it in a variable. You can find out the IP address
using this piece of code:
The code above will check every possible variable which may hold
information about visitor’s IP address. Once it is executed, you will
have visitor IP address stored in $client_ip variable. Now we will have
to create a loop and match visitor’s IP address against each IP address
that we have in our $ip_block array. In the code below there are 3 IF
1) if($client_ip == $ip) – if visitor’s IP addresses exactly matches the IP address defined in $ip_block array. If this is the case we set a variable $blocked to true and exit from the loop.
2) if(strpos($ip, ‘*’) !== false) – if the blocked IP address has * or in other words if we use a mask to define the IP addresses that we need to block. If for example, you define
this will block all visitors with IP addresses 100.100.100.1, 100.100.100.2, 100.100.100.3, 100.100.100…… 255. If we have to check visitors IP address against such mask we split the IP addresses by . and match each of the 4 parts of the IP address. If there is a match, then we consider the IP address to be blocked and exit the loop
3) if(strpos($ip, “-“) !== false) – with the last IF case we check if the visitors IP address should be checked against IP range. In that case we convert the IP address to an integer using ip2long() function and compare that interger with the start and end IP addresses from the range.
At the end we will have a variable $blocked which if set to true means
that visitors IP address is found in our list with blocked IP addresses
and we should block it.
You can redirect the user to another page or just print some message.
The above code is useful if you want to redirect different website visitors to different pages on your website. Using third party service you can find out location country for an IP address and knowing visitor’s country to redirect them to specific language version of your website.