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
php_uname('n') // returns: system01
gethostname() // returns: system01
gethostbyname(gethostname()) // returns ip address
gethostbyname(gethostname() . '.') // returns system01
php -r "var_dump(shell_exec('hostname -f'));"
You can use the following …
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
127.0.0.1. It doesn't matter if you use
hostname -f (if available in your hostname implementation) or
gethostbyaddr("127.0.0.1"), 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
127.0.0.1 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 127.0.0.1 lookup.
There's a little difference between PHP's
hostname -f: The PHP implementation takes the first name assigned to 127.0.0.1, no matter if FQDN or not;
hostname -f tries to find a FQDN in the names and uses the first one it finds.
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.