Here's some sample code:
<?php
$fp = fsockopen($host, $port, $errno, $errstr, $connectTimeout);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
echo "connected\n";
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
I've seen
stream_set_timeout($fp, 5); andsocket_set_option($fp, SOL_SOCKET, SO_RCVTIMEO, array("sec"=>5, "usec"=>0));,
but the read never times out.
I've seen several caveats in the PHP docs for stream_set_timeout():
This function doesn't work with advanced operations like stream_socket_recvfrom(), use stream_select() with timeout parameter instead.
I'd rather not use select() or a loop. What is the canonical way to have a blocking read with timeout?
socket_set_option is for sockets created with socket_create.
stream_set_timeout is for streams, like created by fopen or fsockopen.
Php docs contain example code on how it can be used with fsockopen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With