views:

217

answers:

2

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

A: 

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.)

too much php
This is standard behaviour in most languages/platforms, not just PHP/Windows.
Matthew Scharley
What gets returned if I call `fread($socket)` when the connection is open?
Jenko
Whatever data is waiting to be read
too much php
+4  A: 

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).

Matthew Scharley