lynxus Posted May 13, 2008 Share Posted May 13, 2008 Hi guys, Im trying to figure out how to verify a IP address is valid but failing lol. Mainly because im new to PHP. So any help would be oh so helpfull! My script normally contains quite a lot of IP address's so what would be handy is if one of my vars had a invalid IP it would make my global var of $error = "1" and maybe echo what $var had the bad ip in. So in this instance i would have something like.. $ip1 = _$POST['$ip1']; $ip2 = _$POST['$ip2']; $ip3 = _$POST['$ip3']; lets say ip1 had "10.0.0.0" that would be valid ( 4 octets full and below 256 ) if it had "10.0.0" that would be invalid. not 4 octects if it had "10.0.0.300" that would be invalid.. 4 octect but over 255 .. Does this make any sense? How would i go about validating these vars and then changing my global $error var to 1 if they fail the check? I suppose a function? function checkip($ip){ if $ip = invalid then return "1"; } $error = checkip($ip1); Im guess i sorta see what i need to do? but reallly need help on actually doing it? Many Thanks Graham Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted May 13, 2008 Share Posted May 13, 2008 Well, the function would probably look something like: <?php function verify_ip($ip){ $parts = explode('.',$ip); if(count($parts) < 4){ return FALSE; } foreach($parts as $v){ if(!ctype_digit($parts) || $parts > 255){ return FALSE; } } return TRUE; } ?> Quote Link to comment Share on other sites More sharing options...
rhodesa Posted May 13, 2008 Share Posted May 13, 2008 I would shorten it up with regex and do a lookup: <?php function verify_ip($ip){ if(preg_match('/^(\d{1,3}\.){3}\d{1,3}$/',$ip)) //Make sure it's ###.###.###.### return checkdnsrr($ip); //Check DNS return false; } ?> Quote Link to comment Share on other sites More sharing options...
lynxus Posted May 13, 2008 Author Share Posted May 13, 2008 I would shorten it up with regex and do a lookup: <?php function verify_ip($ip){ if(preg_match('/^(\d{1,3}\.){3}\d{1,3}$/',$ip)) //Make sure it's ###.###.###.### return checkdnsrr($ip); //Check DNS return false; } ?> Hi thanks ( both of you ) I will give them a try and see what happens Thanks -g Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.