Andy
Andy

Reputation: 11985

What's the canonical way to put a read timeout on a stream in PHP?

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); and
socket_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?

Upvotes: 5

Views: 922

Answers (1)

Niko Sams
Niko Sams

Reputation: 4404

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.

Upvotes: 2

Related Questions