7

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

chillers
  • 1,347
  • 2
  • 14
  • 25

4 Answers4

12

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']);
dfsq
  • 182,609
  • 24
  • 222
  • 242
2

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.

Eugen Wesseloh
  • 111
  • 1
  • 3
1

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

Community
  • 1
  • 1
Kamil
  • 11,919
  • 23
  • 72
  • 160
0

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

Community
  • 1
  • 1
Vincent Mimoun-Prat
  • 26,900
  • 13
  • 74
  • 118