How to Validate IPv4 Address in PHP

Validate IP Address in PHP
Validate IP Address in PHP

Today I am going to tell how to validate IPv4 / IP address using PHP. Simple function which will used to check client IP address is valid or not.

Steps to validate IPv4 Address in PHP

  • Split IP address into segments  by dot(.)  using explode function
  • Make sure that there are 4 segments (eg : 192.168.1.45)
  • Make sure that IP cannot start with 0
  • IP segments must be digits & cannot be longer than 3 digits or greater than 255
function validate_ip($ip)
{
//split ip address in to array by dot
$ip_segments = explode('.', $ip);
// Always 4 segments needed
if (count($ip_segments) !== 4)
{
return FALSE;
}
// IP can not start with 0
if ($ip_segments[0][0] == '0')
{
return FALSE;
}
// Check each segment
foreach ($ip_segments as $segment)
{
// IP segments must be digits and can not be
// longer than 3 digits or greater then 255
if ($segment == '' OR preg_match("/[^0-9]/", $segment) OR $segment > 255 OR strlen($segment) > 3)
{
return FALSE;
}
}
return TRUE;
}

//usuage
$ip = validate_ip("192.168.1.43");
if($ip)
{
echo "Valid IP";
} else {
echo "Invalid IP";
}

This function will return boolean true or false

Please don’t forget to share and subscribe to latest updates of the blog. Also any comments and feedback are all welcome!

Thanks!

You May Also Like

Never Miss Any Web Tutorials, Guides, Tips and Free eBooks

Join Our Community Of 50,000+ Web Lovers and get a weekly newsletter in your inbox

 

I hate spam too. Unsubscribe at any time.

2 thoughts on “How to Validate IPv4 Address in PHP”

  1. or

    $ip_a = ‘127.0.0.1’;
    $ip_b = ‘42.42’;

    if (filter_var($ip_a, FILTER_VALIDATE_IP)) {
    echo “This (ip_a) IP address is considered valid.”;
    }
    if (filter_var($ip_b, FILTER_VALIDATE_IP)) {
    echo “This (ip_b) IP address is considered valid.”;
    }

    Reply

Leave a Comment