Home » PHP » PHP IP address based redirect example

PHP IP address based redirect example

This is a IP address redirect example.Check visitor IP address is exist in the IP address list/black list and if exist then visitor redirect to the another location using php.You can put your IP addresses list as line by line with single IP address or CIDR notation.Then check visitor IP address with list and redirect them.


You can put IP addresses as follows in the text file named “ip-address.txt” file.


Now get this IP addresses line by line.You can get more info about reading file line by line in my another post named “PHP read file line by line to an array“.


Get visitor IP address.


Then you need to pass visitor IP address and read IP addresses list as parameters to following function.It will return IP address is exist or not.


Finally get response from above function and redirect them.

Putting all together

Check a particular network/mask combination


Download Blocking IP Address Example (2 KB)


Similar posts

  • Romeo

    Thank you Sunmith for sharing this code with all of us.
    I am however experiencing an error though and I am wondering
    if you can assist please, also please bear with me as I am a newbie to PHP code…

    The error I am getting is:
    Notice: A non well formed numeric value encountered in checkUserIP()

    On both of these line numbers:
    $ipc = substr(join(”, $ipc), 0, $parts[1]);
    $ipux = substr($ipu, 0, $parts[1]);

    I have a about 26 entries of CIDR IP Ranges within my text file:
    and etc…

    I receive this error even if I only have one CIDR IP Range entry within the text file.

    Additional info – I running this on:
    PHP Version 5.3.2

    Any help you can provide would be much appreciated.

    • Enter line by line from top to bottom ip addresses and make sure there are not characters before and after in the ip addresses/CIDR range. Those values as it probably can’t be formatted as a number.Try this.

      $ipc = floatval(substr(join(”, $ipc), 0, $parts[1]));
      $ipux = floatval(substr($ipu, 0, $parts[1]));

      If not success,
      foreach ($ipu as &$v)

      change to
      foreach ($ipu as $v)

      Note there is & mark.


      • Romeo

        Thanks Sunmith,

        This was my first thought to check the text table for any problems with the formatting of the CIDRs and all was good.

        I actually just got it working a few minutes ago without the error by replacing the text file with an array instead.

        Hence I replaced line:

        $cidrs = file($filename, FILE_IGNORE_NEW_LINES);

        $cidrs = array(‘′ ,’′ ,’etc’);

        Works perfect now!
        I suspect there may be an issue with how the file was being accessed on the server, unfortunately it is a hosted server at an ISP so not able to troubleshoot this further…

        Thanks again for the quick reply and help.