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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
aneuryzma
Forum Contributor
Posts: 106
Joined: Sat May 17, 2008 7:03 am

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

Post 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
greip
Forum Commoner
Posts: 39
Joined: Tue Aug 23, 2011 8:23 am
Location: Oslo, Norway

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

Post 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
} 
Post Reply