PHP get domain name

PHP get domain name

Similar question has been asked in stackoverflow before.

See here: PHP $_SERVER[HTTP_HOST] vs. $_SERVER[SERVER_NAME], am I understanding the man pages correctly?

Also see this article:

Recommended using HTTP_HOST, and
falling back on SERVER_NAME only if
HTTP_HOST was not set. He said that
SERVER_NAME could be unreliable on the
server for a variety of reasons,

  • no DNS support
  • misconfigured
  • behind load balancing software


To answer your question, these should work as long as:

  • Your HTTP server passes these values along to PHP (I dont know any that dont)
  • Youre not accessing the script via command line (CLI)

But, if I remember correctly, these values can be faked to an extent, so its best not to rely on them.

My personal preference is to set the domain name as an environment variable in the apache2 virtual host:

# Virtual host

And read it in PHP:

// PHP
echo getenv(DOMAIN_NAME);

This, however, isnt applicable in all circumstances.

PHP get domain name

Leave a Reply

Your email address will not be published.