Validate IP Address in PHP
by Subramanian[ Edit ] 2014-05-31 11:02:41
PHP - Validate IP Address:
A Valid IP address should be satisfied the below conditions.
- First part must be > 0.
- All parts of IP address will be <= 255
- No 0.0.0.0 match
- 00, 000 are not allowed in pairs if first digit starts with 0
- allowed for 0 first digit
The below php function "isValid()" is used to find given ip address is valid or not.
function isValidIp ( $ip )
{
return !preg_match ( '/^([1-9]d|1d{0,2}|2[0-5]{2}).('.
'(0|1?d{0,2}|2[0-5]{2}).){2}(0|1?'.
'd{0,2}|2[0-5]{2})(:d{2,4})?$/',
(string) $ip )
? false
: true;
}
$ip="192.168.0.40";
if( isValidIp ( $ip ) )
{
echo "Valid Ip";
}
else
{
echo "Ip is Not Valid";
}