I am using sockets to send data to a server that may not be responding. So I am trying to define a timeout by using this solution in SO.
Make PHP socket_connect time
You can do this by switching to a non-blocking socket, looping until either a connection is gained or a timeout was reached, then back to blocking again.
// an unreachable address
$host = '10.0.0.1';
$port = 50000;
$timeout = 2;
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
// switch to non-blocking
socket_set_nonblock($sock);
// store the current time
$time = time();
// loop until a connection is gained or timeout reached
while (!@socket_connect($sock, $host, $port)) {
$err = socket_last_error($sock);
// success!
if($err === 56) {
print('connected ok');
break;
}
// if timeout reaches then call exit();
if ((time() - $time) >= $timeout) {
socket_close($sock);
print('timeout reached!');
exit();
}
// sleep for a bit
usleep(250000);
}
// re-block the socket if needed
socket_set_block($sock);
edit: see @letiagoalves answer for an neater solution if you are using sockets created with fsockopen() or stream_socket_client()