gethostbyname() returns the original hostname when resolution fails. Compare the return value and validate the resulting address before using it.
<?php
$host = 'www.example.com';
$ip = gethostbyname($host);
if ($ip === $host || filter_var($ip, FILTER_VALIDATE_IP) === false) {
echo 'Host could not be resolved.';
} else {
echo htmlspecialchars($ip, ENT_QUOTES, 'UTF-8');
}
?>Current approach first; the original tutorial examples below are retained and cleaned up for continued learning and legacy maintenance.
$result = gethostbyname('plus2net.com');
echo $result;
This is the ip address of the host server of plus2net.com.
$result = gethostbyname('plus2net.com');
echo $result;
echo "<br>";
echo gethostbyaddr($result);
The output of the above code is
74.53.25.146
4runner.websitewelcome.com
$result = gethostbynamel('google.com');
print_r($result);
The output of above code is here
Array ( [0] => 74.125.67.100 [1] => 74.125.127.100 [2] => 74.125.45.100 )
$domain = "example.com";
$ip = gethostbyname($domain);
if ($ip === $domain) {
echo "Invalid domain or no IP found.";
} else {
echo "Domain resolves to: " . $ip;
}
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.