Alex Elderson wrote:

>The problem is the "Connection: Close\n\n" header. The webserver close the connection 
>after the first request, if i remove 
>the "Connection: Close\n\n" header the first fgets($web_conn, 128) command will never 
This is because persistent TCP connections are the default behavior of 
HTTP/1.1. In HTTP/1.0, the client had to specifically request a 
persistent connection via the use of a "Connection: Keep-Alive" header 
in the HTTP request. Now (HTTP/1.1) it is quite the opposite; the client 
must specifically request for the server to close the connection with a 
"Connection: Close" header in the HTTP request.

What is happening for you is this:
1) you use PHP socket functions to manually generate an HTTP request to 
a remote Web server
2) The Web server responds to your request and likely includes a 
"Connection: Close" header in the response. It does not, however, close 
the connection itself. It is simply letting you know that it is finished.
3) You do not parse the response or close the connection. You just sit 
there, and thus, nothing happens until a timeout condition is reached.

You are basically implementing a primitive Web client, which is a very 
rewarding experience in terms of the education you provide yourself. It 
requires you, however, to deal with many details of socket programming. 
By leaving the socket open, you are able to send additional HTTP 
requests without all of the overhead of creating/destroying a socket for 
each transaction. This is extremely helpful, of course, for Web pages 
that include several images, so the GET requests for those images can be 
sent on the same connection. Additionally, you can now pipeline your 
requests; you do not have to wait for a response before issuing your 
next request.

If you simply want to make a single request, receive the response, and 
have the connection be terminated, go ahead and include the "Connection: 
Close" header in your HTTP request, and this will request that the Web 
server close the connection for you. Otherwise, you'll need to do it for 
yourself. To close the connection yourself, you need to know when the 
server is finished sending, correct? You do this in two steps:

1) The header portion of the response is terminated by \r\n\r\n (though 
you should be prepared to accept just \n\n).
2) You read exactly how many bytes were specified in the 
"Content-Length" header and close the connection when you receive that.

That's a basic introduction into the semantics of what you're getting 
into. If you still need more information, feel free to ask more 
questions; I enjoy explaining HTTP. Copy me on any responses if you want 
to ensure that I'll not miss your message.



PHP General Mailing List (
To unsubscribe, visit:

Reply via email to