What is the difference between $_SERVER['HTTP_HOST'] and $_SERVER['SERVER_NAME'] in PHP?
When would you consider using one over the other and why?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The
HTTP_HOSTis obtained from the HTTP request header and this is what the client actually used as “target host” of the request. TheSERVER_NAMEis defined in server config. Which one to use depends on what you need it for. You should now however realize that the one is a client-controlled value which may thus not be reliable for use in business logic and the other is a server-controlled value which is more reliable. You however need to ensure that the webserver in question has theSERVER_NAMEcorrectly configured. Taking Apache HTTPD as an example, here’s an extract from its documentation:Update: after checking the answer of Pekka on your question which contains a link to bobince’s answer that PHP would always return
HTTP_HOST‘s value forSERVER_NAME, which goes against my own PHP 4.x + Apache HTTPD 1.2.x experiences from a couple of years ago, I blew some dust from my current XAMPP environment on Windows XP (Apache HTTPD 2.2.1 with PHP 5.2.8), started it, created a PHP page which prints the both values, created a Java test application usingURLConnectionto modify theHostheader and tests taught me that this is indeed (incorrectly) the case.After first suspecting PHP and digging in some PHP bug reports regarding the subject, I learned that the root of the problem is in web server used, that it incorrectly returned HTTP
Hostheader whenSERVER_NAMEwas requested. So I dug into Apache HTTPD bug reports using various keywords regarding the subject and I finally found a related bug. This behaviour was introduced since around Apache HTTPD 1.3. You need to setUseCanonicalNamedirective toonin the<VirtualHost>entry of theServerNameinhttpd.conf(also check the warning at the bottom of the document!).This worked for me.
Summarized,
SERVER_NAMEis more reliable, but you’re dependent on the server config!