Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP function to validate IPv4 and IPv6 using regex

Tags:

I'm needing to create a function for IPv4 and v6 that I cause use local ip's as well.

What I know is a valid IPv4 ranges from 0.0.0.0 to 255.255.255.255 What I know of IPv6 is limited however as despite it being around for a while I haven't really looked much into it til today. But I want to future proof the function I am making a little bit while keeping it a bit retro for the time being. I'm not sure what the valid ranges are for IPv6.

Anyway In general what I am thinking is a function to the extent of

function validateIP($ip, $vSix = NULL) {     if($vSix !== NULL)     {       if(preg_match([regex-to-validate-ipv6], $ip))       {         return true;       }       else       {         return false;       }     }      if(preg_match([regex-to-validate-ipv4], $ip))     {       return true;     }     else     {       return false;     } } 

my thing is I suck with regex so I have no idea how to write one that will validate v4 or 6. Also a sanity check on the above function concept would be nice as well.

like image 405
chris Avatar asked Mar 07 '12 19:03

chris


1 Answers

Check PHP's filter_var function. It has a number of validators, including IPv4 and IPv6.

$isValid = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4); // $isValid can be evaluated as boolean, as it's FALSE if validation fails. 
like image 173
Morgon Avatar answered Sep 21 '22 00:09

Morgon