Home » Php » PHP if IP or Domain detect function

PHP if IP or Domain detect function

Posted by: admin July 12, 2020 Leave a comment

Questions:

Is there a way to detect if a string is a Ip or Domain using php, example below.

$string = "http://192.168.0.0";
$string = "http://example.com";

So if the string is a IP the script/function will do something if it detects it as Domain it will do something else.

Thank you

How to&Answers:

You can test it simply like this:

$isIP = (bool)ip2long($_SERVER['HTTP_HOST']);

The function ip2long will return false is host is not a valid IP address like domain name. The benefit of using ip2long function is that it also validates provided IP address. So for example address is 4.4.4.756 will give you false.

So to test a given string you can do:

$string = "http://192.168.0.0";
$parts = parse_url($string);
$isIP = (bool)ip2long($parts['host']);

Answer:

You can use regular expressions.

Here you can find example:

Regular expression to match DNS hostname or IP Address?

Code / regex patterns:

ValidIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";

ValidHostnameRegex = "^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$";

How to use regex in php:

preg-match manual at php.net

Answer:

You also may compare HTTP_HOST and SERVER_ADDR.
For IP v6 you should also trim square brackets on HTTP_HOST.

$isIP = @($_SERVER['SERVER_ADDR'] === trim($_SERVER['HTTP_HOST'], '[]'));

seems to be more efficient than regex, but not sure if ip2long aproach would be more efficient.

Answer:

You have the regular expressions on that SO question: Regular expression to match DNS hostname or IP Address?

And you will need to use the PHP function: preg_match