NYCPHP Meetup

NYPHP.org

[nycphp-talk] Best practice for comparing IP addresses

Hans Zaunere zaunere at yahoo.com
Sun Jun 1 13:31:18 EDT 2003


--- Phil Powell <soazine at erols.com> wrote:
> Consider the following lines of code:
> 
> if ($hasEnteredNick == 1 && file_exists("$pathStart/banned_ips.xml")) {
>     $fileID = fopen("$pathStart/banned_ips.xml") or die("Cannot open file
> $pathStart/banned_ips.xml");
>     $stuff = fread($fileID, filesize("$pathStart/banned_ips.xml"));
> fclose($fileID);
>     $parser = xml_parser_create();
>     xml_parse_into_struct($parser, $stuff, $bannedIPArray, $extraStuff);
>     xml_parser_free($parser);
>     $yourIPArray = explode(".", $REMOTE_ADDR);
>     for ($i = 0; $i < sizeOf($bannedIPArray); $i++) {
>      $ipArray = explode($bannedIPArray[$i][attributes][IP], ".");          
>      if (($bannedIPArray[$i][attributes][NICK] === $nick ||
>          implode(".", array_pop($yourIPArray)) == implode(".",
> array_pop($ipArray))
>          ) &&
>          $bannedIPArray[$i][attributes][NICK] !== "admin"
>         ) {
>       // NICKNAME FOUND IN banned_ips.xml FILE - THEY HAVE BEEN BANNED FROM
> CHATROOM
>       $hasEnteredNick = 0;
>       if ($bannedIPArray[$i][attributes][NICK] === $nick) {
>        $errorMsg = "You are using a banned nickname, please select
> another";
>       } else {
>        $errorMsg = "The user at this machine ($REMOTE_ADDR) has been banned
> from the chatroom";
>       }
>       break;
>      }
>     }
>          
>    }
> 
> What I want to do is compare an IP address from a parsed XML file with the
> user's IP address.  If a match is found only in the first three numbers
> (xx.xx.xx.*) then action is taken.  I thought about using the following
> algorithm to do so, but does anyone else have a better suggestion?  I am
> not accustomed to either implode, explode or array_pop, so I am not sure if
> they are being used properly w/o extensive testing.


This may be a handy function,

http://www.php.net/manual/en/function.ip2long.php

and the usernotes for that page are very nice, too.  Nevertheless, another
potential pCom! :)

H





More information about the talk mailing list