Question

How can a PHP script detect if a socket has been closed by the remote party?

Was it helpful?

Solution

From socket_read():

socket_read() returns the data as a string on success, or FALSE on error 
(including if the remote host has closed the connection). The error code can 
be retrieved with socket_last_error(). This code may be passed to 
socket_strerror() to get a textual representation of the error.

This is the fairly standard approach to detecting if a socket is closed in most languages. I don't believe PHP offers a direct event-style notification (except perhaps something in PEAR).

OTHER TIPS

fread($socket) returns empty string, instantly, without waiting for the socket to timeout.

(No, this is not a real answer, but this is the hackish solution I have in place in my code ATM. This behaviour might also be windows-specific.)

This is not a direct answer to the question, but maybe valuable note. If you call socket_close($socket); in multiple places and want to check wether you already closed the socket before or not, you can do it by using following comparison:

    if (get_resource_type($socket) === 'Unknown') {
        exit;
    }

I found it by dumping socket before and after closing var_dump($socket);

  • before closing resource(5) of type (Socket)
  • after closing resource(5) of type (Unknown)

But it wont tell you wether socket is closed by other side or not. Basicly when connection is established there are always two sockets - one for each side. So get_resource_type will only check your own resource, not the other side.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top