0

I have to write a PHP script that works as a client against another HTTP Server. This Server ignores the HTTP Connection:Close header and keeps the TCP connection open unless it is closed by the client. And here is my dilemma. I (the client) have to deciede when a HTTP request/response has finished and then close the connection. Simply use:

$data = file_get_contents($url);

.. won't work, as file_get_contents returns only if the connection timeout (default 30 seconds) has reached.

So I have to write my own read - loop like this (pseudo code):

$sock = fsockopen(...);
$data = '';
while($line = fgets($sock)) {
    $data .= $line;
    if(http_package_recieved()) {
        break;
    }
}

Unfortunately there is no Content-Length header in the response. My question is, how the function

http_package_recieved()

... should look like.

Greets Thorsten

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • 1
    The question was downvoted today - 5 years after having posted. Can the downvoter explain the reasoning behind that? – hek2mgl Jun 10 '15 at 12:32

5 Answers5

3

You can check if $line is empty to see if the server isn't sending anything. You can also set a small read timeout on the socket with stream_set_timeout() , and then inside the loop check stream_get_meta_data() to see if it has been reached in order to break out.

Fanis Hatzidakis
  • 5,282
  • 1
  • 33
  • 36
2

You'd be better of using a library, such as cURL (http://uk.php.net/manual/en/intro.curl.php), to handle this. The HTTP spec isn't simple: https://www.rfc-editor.org/rfc/rfc2616 (see Section 4.4) and you'd likely miss something crucial.

Community
  • 1
  • 1
Rushyo
  • 7,495
  • 4
  • 35
  • 42
2

If it doesn't close the connection and it doesn't tell you the total length of the response, you have no way to know whether all the data has been received.

You could specify a maximum time interval between packets, but that won't be reliable.

Artefacto
  • 96,375
  • 17
  • 202
  • 225
1

When the entity ends is either guided by:

It's possible you may have to process this chunked transfer encoding if you get this header. There are libraries to do so.

Bruno
  • 119,590
  • 31
  • 270
  • 376
  • Transfer-Encoding: chunked, I *have*. I'll read about this. thanks. – hek2mgl Sep 15 '10 at 14:06
  • I'd strongly recommend using a library to do so, unless you have a good reason not to. libcurl is available via PHP (as @Rushyo said). – Bruno Sep 15 '10 at 14:09
0

feof($sock) would be OK

baton
  • 297
  • 1
  • 3