86

I want to get the domain name for where the script is running. How can that be done with PHP? I see that $_SERVER['HTTP_HOST'] as well as $_SERVER['SERVER_NAME'] contain this information. Will that variable always work and should I use one over the other?

Thank you.

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Francisc
  • 77,430
  • 63
  • 180
  • 276
  • That does answer part of my question about using SERVER_NAME over the other, but is this the right way to do this in PHP? (is the other part) Thank you. – Francisc Mar 23 '11 at 11:57

2 Answers2

90

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: http://shiflett.org/blog/2006/mar/server-name-versus-http-host

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, including:

  • no DNS support
  • misconfigured
  • behind load balancing software

Source: http://discussion.dreamhost.com/thread-4388.html

Community
  • 1
  • 1
Mukesh Chapagain
  • 25,063
  • 15
  • 119
  • 120
  • 1
    HTTP_HOST seems right to me. SERVER_NAME worked fine until we started using Docker, then just gave us "localhost". Just note that HTTP_HOST will give you the sub-domain too. – Autumn Leonard Feb 15 '17 at 20:13
7

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

  • Your HTTP server passes these values along to PHP (I don't know any that don't)
  • You're not accessing the script via command line (CLI)

But, if I remember correctly, these values can be faked to an extent, so it's 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
setEnv DOMAIN_NAME example.com

And read it in PHP:

// PHP
echo getenv(DOMAIN_NAME);

This, however, isn't applicable in all circumstances.

0b10011
  • 18,397
  • 4
  • 65
  • 86
xzyfer
  • 13,937
  • 5
  • 35
  • 46