Use getservbyname() when you need to resolves a service name and protocol to a registered port number in a PHP application. The examples below show the actual operation and its limitations.
What Is getservbyname() in PHP?
Resolves a service name and protocol to a registered port number. The exact signature supported by your installation depends on its PHP version and enabled extensions.
Its syntax is:
getservbyname(string $service, string $protocol): int|false
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
var_dump(getservbyname("http","tcp"));
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
var_dump(getservbyname("domain","udp"));
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
$serviceName = "https"; $port = getservbyname($serviceName,"tcp"); echo $port === false ? "Unknown" : "Port: " . $port;
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
Consults the OS service database, which can differ between systems.
Comparison With Related Functions
| Approach | Difference |
|---|---|
getservbyname() | Resolves a service name and protocol to a registered port number. |
| Related operation | getservbyport() maps a port/protocol pair back to a service name. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring the function-specific limitation | Consults the OS service database, which can differ between systems. |
| Confusing this function with a related operation | getservbyport() maps a port/protocol pair back to a service name. |
Key Takeaways
- Resolves a service name and protocol to a registered port number.
- Consults the OS service database, which can differ between systems.
- getservbyport() maps a port/protocol pair back to a service name.
Use getservbyname() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.