Take the 2-minute tour ×
Webmasters Stack Exchange is a question and answer site for pro webmasters. It's 100% free, no registration required.

For my website i use this php code to block ip addresses.

$deny = array("111.111.111", "222.222.222", "333.333.333");
if (in_array ($_SERVER['REMOTE_ADDR'], $deny)) {
   header("location: http://www.google.com/");
} ?>

How to re-edit this code to block ip addresses like all addresses starting from "111." or "222." like that?

Thanks in advance!

share|improve this question

closed as off-topic by Zistoloen, John Conde Apr 17 at 11:16

  • This question does not appear to be about webmastering within the scope defined in the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

Use regex in here. –  Ultra Apr 17 at 10:03
is it possible through php? –  Kiran RS Apr 17 at 10:55
RTFM: php.net/manual/en/function.preg-match.php –  Ultra Apr 17 at 14:13

1 Answer 1

You can try something like this:

$deny = array("111.111.111", "222.222.222", "333.333.333");
foreach ($deny as $denyip) {
  if (strpos($_SERVER['REMOTE_ADDR'], $denyip)===0) {
    header("location: http://www.google.com/");

This basically loops through all denied IP's and checks if the user's IP starts with the IP written in the deny list. It will also work if you put full ip in the deny list, so you can combine full and partial ip's.

Notice the === in comparison. It means that the position must really be 0, which means that user IP begins with the ip in the deny list. If you only put == it will block all users who are not found in the deny list too, since false==0 in php, so that is why you must use === instead.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.