Use gethostbyname() when you need to resolves a hostname to one IPv4 address in a PHP application. The examples below show the actual operation and its limitations.
What Is gethostbyname() in PHP?
Resolves a hostname to one IPv4 address. The exact signature supported by your installation depends on its PHP version and enabled extensions.
Its syntax is:
gethostbyname(string $hostname): string
Parameters and return value: The parameter types, optional arguments, references, and return type are shown in the signature above. Optional parameters are marked with an ellipsis in this reference signature.
Example 1: Basic Usage
<?php
echo gethostbyname("localhost");
Result: Run the example in an environment that supports the function. Any values depending on operating-system state, installed extensions, process configuration, or network access must be checked on the target server.
Example 2: Different Input or Behavior
<?php
echo gethostbyname("example.invalid") === "example.invalid" ? "Unresolved" : "Resolved";
Result: Run the example in an environment that supports the function. Any values depending on operating-system state, installed extensions, process configuration, or network access must be checked on the target server.
Practical Example: Applying the Function
<?php
$hostname = "localhost"; $address = gethostbyname($hostname); echo $address === $hostname ? "DNS unavailable" : "IPv4: " . $address;
Result: Run the example in an environment that supports the function. Any values depending on operating-system state, installed extensions, process configuration, or network access must be checked on the target server.
Important Behavior and Edge Cases
Failures may return the original hostname; validate resolved IPs and do not treat DNS as authorization.
Comparison With Related Functions
| Approach | Difference |
|---|---|
gethostbyname() | Resolves a hostname to one IPv4 address. |
| Related operation | gethostbynamel() can return multiple IPv4 addresses. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring the function-specific limitation | Failures may return the original hostname; validate resolved IPs and do not treat DNS as authorization. |
| Confusing this function with a related operation | gethostbynamel() can return multiple IPv4 addresses. |
Key Takeaways
- Resolves a hostname to one IPv4 address.
- Failures may return the original hostname; validate resolved IPs and do not treat DNS as authorization.
- gethostbynamel() can return multiple IPv4 addresses.
Use gethostbyname() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.