PHP发送http header的注意事项

在测试发送http header的时候,总是碰到一些奇奇怪的问题。无法理解啊,先记录如下,以后再找原因。

http GET例子

$header = "
GET /test2.php?get=1 HTTP/1.1
Host: 127.0.0.1
Connection: Close

";

不要忘了最后的空行。 或是另一种写法:

$header = "";
$header .= "GET /test2.php?get=1 HTTP/1.1\r\n";
$header .= "Host: 127.0.0.1\r\n";
$header .= "Connection: Close\r\n\r\n"; //GET时这里多一个换行符

http POST例子

$header = "
POST /test2.php HTTP/1.1
Host: 127.0.0.1
Content-Type: application/x-www-form-urlencoded
Connection: Close
Content-Length: 15

key=1&key2=test
";

或是

$header = "";
$header .= "POST /test2.php HTTP/1.1\r\n";
$header .= "Host: 127.0.0.1\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Connection: Close\r\n";
$header .= "Content-Length: 15\r\n"; //POST时长度是必须的。而且要正确。= strlen('key=1&key2=test')
$header .= "\r\n"; //POST时这里在多一行
$header .= "key=1&key2=test\r\n";

 

发送http GET时,Connection的后面必需要多一行, http POST时不需要,不然接收不到post的数据,接收不到header post数据的问题害我测试了一下午~~。

发送http POST时, Content-Length是必需的,而且要正确。 Content-Length与POST的值之间也必需多一行。

GET与POST的这点区别浪费了我一天的时候。 原因不是很明白了,待查吧。

测试环境是nginx+ PHP/5.2 与 apache + PHP/5.4