Reputation: 3827
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.
Upvotes: 5
Views: 9926
Reputation: 1204
gethostbyaddr(gethostbyname(gethostname()));
This returns the FQDN for me while everything else just returns localhost or hostname.
Upvotes: 11
Reputation: 179
For debian default config the fqdn can be retrieved with:
gethostbyaddr('127.0.1.1');
Upvotes: 1
Reputation: 13107
You can use the following …
echo gethostbyaddr("127.0.0.1");
This may give a you FQDN, or localhost
(see below for the cause of this).
… but:
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 gethostbyaddr('127.0.0.1')
and 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.
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.
Upvotes: 4