1

My question is very similar to this question but in my case I am wanting to know if the stream returned by stream_socket_client is open and writeable.

I know that stream_socket_client will return FALSE if the stream could not be opened, but I am needing to detect later on if the stream has been closed by the server (or closed due to some network error, for example).

At the moment I'm just doing...

$fp = stream_socket_client($apns_url, $error_code, $error_string, $timeout_secs, STREAM_CLIENT_CONNECT, $ctx);
//looping through / sending data
if (!fp) {
    //re-open connection
}

...but I'm not sure if my if (!fp) {...} check is sufficient?

ezio4df
  • 3,541
  • 6
  • 16
  • 31
ban-geoengineering
  • 18,324
  • 27
  • 171
  • 253

2 Answers2

4

Use stream_get_meta_data for checking if stream is writable.

 $meta = stream_get_meta_data($fp);

 if(is_writable($meta['uri'])) { 
 // stream is writable
 }

Use feof for checking if stream is open.

  • Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout);
  • Hey, I am using PHP7.4.3 Win10 x64 And `stream_get_meta_data` doesn't contain uri index. What can be the problem?? – ezio4df May 25 '20 at 12:02
  • @aXuser264 can you open a question on that posting more code? You should get output that would contain `uri` index also. Are you behind a proxy? –  May 25 '20 at 19:01
2

Try checking for end of file instead of checking if it is false

while (!feof($fp)) {...}
Nitin
  • 898
  • 1
  • 9
  • 25