Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP if IP or Domain detect function

Tags:

php

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

like image 270
chillers Avatar asked Oct 20 '12 09:10

chillers


3 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']);
like image 151
dfsq Avatar answered Nov 27 '22 03:11

dfsq


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.

like image 40
Eugen Wesseloh Avatar answered Nov 27 '22 04:11

Eugen Wesseloh


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

like image 27
Kamil Avatar answered Nov 27 '22 03:11

Kamil