phpapacheserver-name

How to find server domain name for SMTP from PHP?


I have cPanel servers which run the same script, but I've hard coded the server name in to the code as I can't find anywhere to grab the actual server domain.

Imagine 3 cPanel servers and these are the server domains:

apple.hosting.com
banana.hosting.com
carrot.hosting.com

While running a PHP script to send mail via SMTP, I need to connect to the server and want to use the server name that would be provided for secure connections.

I don't want to create an array of the IP addresses and then have it compare, as that won't work with dedicated IP addresses.

I tried ini_get('SMTP'), which just returns a useless 'localhost'.

I tried ini_get_all(null,false), and no joy.

I checked the $_SERVER global, but only the domain being accessed appeared.

The only thing that returned the server name was phpinfo().


Solution

  • It took a while to find this, and in composing the question, I found the answer. Rather than waste what I think is a good question (since I couldn't find the answer easily), here it is:

    New as of PHP 5.3:

    gethostname();
    

    That's it, nice and sweet.

    Read more here: PHP function gethostname