Webmasters Stack Exchange is a question and answer site for pro webmasters. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 '14 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. – Szymon Toda Apr 17 '14 at 10:03
is it possible through php? – Kiran RS Apr 17 '14 at 10:55

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.