TechniqueFor high-level sockets, use the socket_set_timeout() function: <?php $sock = fsockopen("www.slashdot.org", 80, $errstr, $errno, 30); if(!$sock) { dir($errstr); } socket_set_timeout($sock, 60); fwrite($sock,"GET / HTTP/1.0\n\n"); $res = fread($sock, 2000); $status = socket_get_status($sock); if ($status['timed_out']) { print "Timeout\n"; fclose($sock); } else print $res; ?> CommentsIf you use blocking sockets but still want the read operation to time out after a certain period, you should make use of socket_set_timeout() function. It takes the socket descriptor as the first parameter, and number of seconds and microseconds specifying the timeout as the second and third parameters. After the socket read operation exits, the way to find out whether timeout occurred is to call the socket_get_status() function and check the 'timed_out' entry in the array it returns. If the 'timed_out' entry is true, the socket read timed out; otherwise , the operation was completed successfully. See the next section for more information about socket_get_status() . |