Page 1 of 1

I need to know what code to write when a connection fails.

Posted: Fri Sep 16, 2011 1:12 pm
by aneuryzma
I need to know what code to write when a connection fails.
In all tutorials I usually find:

Code: Select all

$fp = stream_socket_client("tcp://www.example.com:80", $errno, $errstr, 30);
if (!$fp) {
   print "some error" //HERE I WANT SOME SERIOUS CODE
}
...
But I actually want to try the connection again after a while, and probably several times, but not infinitely.

Could you show me some example of code to implement in the if statement ?
thanks

Re: I need to know what code to write when a connection fail

Posted: Fri Sep 16, 2011 1:47 pm
by greip
You could do something like this:

Code: Select all

 for ( $tries = 5, $interval = 2, $fp = false; !$fp && $tries > 0; $tries-- ) {
  if ( !($fp = stream_socket_client("tcp://www.example.com:80", $errno, $errstr, 30)) ) {
    error_log ( "Failed to ..." );
    sleep ( $interval );
  }
}
if ( $fp ) {
  // you have the handle - do the work
}