Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

sockets

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?

like image 539
Andy Avatar asked Nov 04 '22 13:11

Andy


1 Answers

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.

like image 196
Niko Sams Avatar answered Nov 15 '22 06:11

Niko Sams