According to RFC 2616, which defines HTTP/1.1, the Host:
header is mandatory.
A client MUST include a Host header field in all HTTP/1.1 request messages .
But the PHP manual implies that it could be empty:
'HTTP_HOST': Contents of the Host: header from the current request, if there is one.
In which situations could this header, and thus $_SERVER['HTTP_HOST']
, be empty? Could my application depend on its being there?
It can be empty in HTTP 1.0. If no host header is specified, virtual hosting won't work at all, so the default vhost in your web server will be used.
I just tested this myself; in PHP under Nginx the $_SERVER['HTTP_HOST']
variable got set to the name of the virtual host, which is _
in my case. But that also depends on your fastcgi_params configuration in Nginx.
On shared hosting this is not important since the default vhost will be set to some information page from the hosting company, and so your script will not be run. Could be a good thing to keep in mind for your own server though.
Crawlers (e.g. google), scrapers or even perfectly legal scripts interfacing with your API may accidentally or ignorantly skip the Host header.
I added this answer because this question came up on google when I looked for the same thing.