wormhit wormhit - 1 year ago 126
PHP Question

How to get current system FQDN in php-cli?

Is there a way to retrieve current system fully qualified domain name using php-cli?

What I'm looking for is php function to retrieve the same thing that hostname -f is doing:

$ hostname -f #returns needed: system01.dev.lan

I tried following:

php_uname('n') // returns: system01
gethostname() // returns: system01
gethostbyname(gethostname()) // returns ip address
gethostbyname(gethostname() . '.') // returns system01

$_SERVER dose not exist (because only cli env)

Again, I know I can do this

php -r "var_dump(shell_exec('hostname -f'));"

But for this trivial task, I think php should have built in functionality to retreive fqdn.

lxg lxg
Answer Source

You can use the following …

echo gethostbyaddr("");

This may give a you FQDN, or localhost (see below for the cause of this).


even if this works, it is not guaranteed to, and is not at all portable.

Why is that?

What you want is basically a reverse DNS lookup for the IP address It doesn't matter if you use hostname -f (if available in your hostname implementation) or gethostbyaddr(""), the system must always occupy the resolver to find a FQDN for an IP address.

Now if you have a FQDN entry for your IP address in your /etc/hosts, then the resolver is able to find the FQDN locally, otherwise it must make a reverse DNS lookup.

This is by design, nothing you can do about it. Fully qualified domain names are the business of DNS, local hosts were never supposed to know about them. Even the /etc/hosts entry is more of a hack. (Though a common one, many mail servers need it, too.)

That's why the solution is not portable: If your application is deployed on a server where no FQDN for is in the /etc/hosts file, then it will just return the simple host name.

And, obviously, a DNS server can't give you a domain name for a lookup.

There's a little difference between PHP's gethostbyaddr('') and hostname -f: The PHP implementation takes the first name assigned to, no matter if FQDN or not; hostname -f tries to find a FQDN in the names and uses the first one it finds.

The shell_exec approach appears valid, but if you'd need to avoid shell commands, you could try reading and parsing /etc/hosts directly in PHP; as the syntax is quite simple.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download