PHP教程:HTTP1.0協議下HTTP_HOST爲空的根本原因

昨天xuepeng師兄提出一個問題是PHP在獲取 $_SERVER['HTTP_HOST']爲空, 經過我翻看RFC文檔以及測試,得出結論如下:
在http 1.1中, host字段是不能爲空的,如果爲空, 服務器會認爲是bad request
但是在http 1.0中, host字段是可以爲空的. 如:
1<?php
2$fp = fsockopen("localhost", 80, $errno, $errstr, 30);
3 
4$header = "GET /index.php";
5$header .= " HTTP/1.0\r\n";
6 
7$header .= "Connection:Close\r\n\r\n";
8fwrite($fp, $header);
9    echo fread($fp, 1024);
10fclose($fp);
11?>
其中,主機的index.php只是var_dump($_SERVER['HTTP_HOST']);
可以看到,當你指明使用http 1.0協議的時候, 請求正常,返回結果是false;
但是如果你指明協議是http 1.1 :
1<?php
2$fp = fsockopen("localhost", 80, $errno, $errstr, 30);
3 
4$header = "GET /index.php";
5$header .= " HTTP/1.1\r\n";
6 
7$header .= "Connection:Close\r\n\r\n";
8fwrite($fp, $header);
9    echo fread($fp, 1024);
10fclose($fp);
11?>
則結果是400 bad request;
究其原因是因爲在HTTP1.0的時候, 並沒有設想到現在有這麼多服務器共用一個IP的情況(virtual host), 而在HTTP1.1的時候,加入了對多個HOST共用一個IP的支持.
以下文字摘自RFC2616:
14.23 Host
The Host request-header field specifies the Internet host and port
number of the resource being requested, as obtained from the original
URI given by the user or referring resource (generally an HTTP URL,
Fielding, et al. Standards Track [Page 128]
RFC 2616 HTTP/1.1 June 1999
as described in section 3.2.2). The Host field value MUST represent
the naming authority of the origin server or gateway given by the
original URL. This allows the origin server or gateway to
differentiate between internally-ambiguous URLs, such as the root “/”
URL of a server for multiple host names on a single IP address.
Host = “Host” “:” host [ ":" port ] ; Section 3.2.2
A “host” without any trailing port information implies the default
port for the service requested (e.g., “80″ for an HTTP URL). For
example, a request on the origin server for
would properly include:
GET /pub/WWW/ HTTP/1.1
Host: www.w3.org
A client MUST include a Host header field in all HTTP/1.1 request
messages . If the requested URI does not include an Internet host
name for the service being requested, then the Host header field MUST
be given with an empty value. An HTTP/1.1 proxy MUST ensure that any
request message it forwards does contain an appropriate Host header
field that identifies the service being requested by the proxy. All
Internet-based HTTP/1.1 servers MUST respond with a 400 (Bad Request)
status code to any HTTP/1.1 request message which lacks a Host header
field.
以下省略…..
後記: 雖然HTTP_HOST不能缺失, 但是可以爲空值 (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.23):
If the requested URI does not include an Internet host name for the service being requested, then the Host header field MUST be given with an empty value.
作者: Laruence
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章