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
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']);
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With