stream_set_timeout

(PHP 4 >= 4.3.0, PHP 5)

stream_set_timeoutУстанавливает значение тайм-аута на потоке

Описание

bool stream_set_timeout ( resource $stream , int $seconds [, int $microseconds = 0 ] )

Устанавливает значение тайм-аута на потоке stream, равное сумме параметров seconds и microseconds.

Когда время работы потока истекает, ключ 'timed_out' массива, возвращаемого функцией stream_get_meta_data(), устанавливается в значение TRUE, хотя ошибка или предупреждение не генерируется.

Список параметров

stream

Целевой поток.

seconds

Секунды в устанавливаемом тайм-ауте.

microseconds

Микросекунды в устанавливаемом тайм-ауте.

Возвращаемые значения

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Список изменений

Версия Описание
4.3.0 Начиная с PHP 4.3 эта функция может (потенциально) работать на любом типе потока. В PHP 4.3 потоки, основанные на сокетах - это единственный тип потоков, поддерживаемый в ядре PHP, хотя потоки из других расширений могут поддерживать эту функцию.

Примеры

Пример #1 Пример использования stream_set_timeout()

<?php
$fp 
fsockopen("www.example.com"80);
if (!
$fp) {
    echo 
"Невозможно открыть сокет\n";
} else {

    
fwrite($fp"GET / HTTP/1.0\r\n\r\n");
    
stream_set_timeout($fp2);
    
$res fread($fp2000);

    
$info stream_get_meta_data($fp);
    
fclose($fp);

    if (
$info['timed_out']) {
        echo 
'Истекло время соединения!';
    } else {
        echo 
$res;
    }

}
?>

Примечания

Замечание:

Эта функция не работает с продвинутыми операциями, такими, как stream_socket_recvfrom(). Используйте вместо неё stream_select() с параметром тайм-аута

Эта функция раньше вызывалась через set_socket_timeout() и позднее через socket_set_timeout(), но это использование устарело.

Смотрите также

  • fsockopen() - Открывет соединение с интернет сокетом или доменным сокетом Unix
  • fopen() - Открывает файл или URL

Коментарии

Автор:
I have found it required to add 

"stream_set_blocking($fp, FALSE )" 

prior to any fgets(), fread(), etc. to prevent the code from hanging up when remote files are called and the response is slow.
2005-02-17 07:37:10
http://php5.kiev.ua/manual/ru/function.stream-set-timeout.html
stream_set_timeout() is not suitable for such files as UNIX-devices (/dev/...), i suggest to use select() instead with desirable timeout value - that works well.
2006-02-25 04:41:06
http://php5.kiev.ua/manual/ru/function.stream-set-timeout.html
If you are using fsockopen() to create a connection, first going to write into the stream and then waiting for the reply (e.g. simulating HTTP request with some extra headers), then stream_set_timeout() must be set only after the write - if it is before write, it has no effect on the read timeout :-( 
Noticed at least on PHP/4.3.10
2006-08-01 11:10:20
http://php5.kiev.ua/manual/ru/function.stream-set-timeout.html
I have found that in order to actually stop the socket from timing out the script, you must call stream_get_meta_data and check for a timeout within the loop reading from the socket.

Example:

<?php
$sock 
fsockopen($host80$errno$errstr30);
if(!
$sock){
    echo 
"Unable to get server status";
}else{
   
$out "GET /server.php HTTP/1.1\r\n";
   
$out .= "Host: $host\r\n";
   
$out .= "Connection: Close\r\n\r\n";

   
fwrite($sock$out);

   
stream_set_blocking($fpFALSE );
   
stream_set_timeout($sock$timeout);
   
$info stream_get_meta_data($sock);

    while (!
feof($sock) && !$info['timed_out']) {
       
$file .= fgets($sock4096);
       
$info stream_get_meta_data($sock);
    }

   
fclose($sock);
?>
2006-11-20 08:33:09
http://php5.kiev.ua/manual/ru/function.stream-set-timeout.html
Here is a working example for loops:

<?php
// Timeout in seconds
$timeout 5;

$fp fsockopen("www.server.com"80$errno$errstr$timeout);

if (
$fp) {
       
fwrite($fp"GET /file.php HTTP/1.0\r\n");
       
fwrite($fp"Host: www.server.com\r\n");
       
fwrite($fp"Connection: Close\r\n\r\n");

       
stream_set_blocking($fpTRUE);
       
stream_set_timeout($fp,$timeout);
       
$info stream_get_meta_data($fp);

        while ((!
feof($fp)) && (!$info['timed_out'])) {
               
$data .= fgets($fp4096);
               
$info stream_get_meta_data($fp);
               
ob_flush;
               
flush();
        }

        if (
$info['timed_out']) {
                echo 
"Connection Timed Out!";
        } else {
                echo 
$data;
        }
}
?>
2007-03-12 11:39:05
http://php5.kiev.ua/manual/ru/function.stream-set-timeout.html
I didn't have much luck with the suggestions below (although I likely applied them wrong). 
Instead, I used stream_context_create() and set an http option for timeout. I fed that context into file_get_contents() and voila!

To my desperate friend below: the https transport can also use the http stream context options. I haven't verified this works as I don't have a slow responding ssl to test on. But if you are still stressing, give the below a shot (you may need to modify a bit...) 

<?php
    $timeout 
5*60;
   
$options = array(
         
'http'=>array(
           
'method'=>"GET",
           
'header'=>"Accept-language: en\r\n",
             
'timeout' => $timeout 
             
)
        );
   
$context stream_context_create($options);
   
$contents file_get_contents($sourcefalse$context);
?>

Yes...that is a 5 minute timeout.
2009-11-29 19:53:23
http://php5.kiev.ua/manual/ru/function.stream-set-timeout.html
In case anyone is puzzled, stream_set_timeout DOES NOT work for sockets created with socket_create or socket_accept. Use socket_set_option instead.

Instead of:
<?php
stream_set_timeout
($socket,$sec,$usec);
?>

Use:
<?php
socket_set_option
($socketSOL_SOCKETSO_RCVTIMEO, array('sec'=>$sec'usec'=>$usec));
socket_set_option($socketSOL_SOCKETSO_SNDTIMEO, array('sec'=>$sec'usec'=>$usec));
?>
2010-10-29 12:29:35
http://php5.kiev.ua/manual/ru/function.stream-set-timeout.html
This function seems to have no effect when running as a CLI script, see http://bugs.php.net/bug.php?id=36030
2011-05-18 04:28:20
http://php5.kiev.ua/manual/ru/function.stream-set-timeout.html
Автор:
Just in case someone stumbles into my situation... I was trying to get the microseconds part to work and it just wasn't working as expected.

Assuming blocking mode is true and I use 

<?php stream_set_timeout($s10);?>

I get a 1s delay as expected. However when I do 

<?php stream_set_timeout($s0500);?>

I expect a 500microsecond delay but I get no delays at all. However when i do this

<?php stream_set_timeout($s0500000);?>

I get a 500 microsecond delay which is what I was expecting
2014-05-27 23:25:02
http://php5.kiev.ua/manual/ru/function.stream-set-timeout.html
Another note alread states that blocking-reads may be an issue, if the counterpart responds very slowly - or not at all. The stream timeout may not work as expected in such a situation.

However, php.net provides very little information on how to use non-blocking reading operations. Here's a code sample:

<?php
        stream_set_timeout
($c$timeout);
       
$data '';
        while (
is_resource($c) && !feof($c)) {
           
// Use non-blocking reading for first loop
           
if (($data === '') and ($timeout 0)) {
               
stream_set_blocking($cfalse);
               
$endtimeOut time() + $timeout;
               
$str '';
                while ((
time() < $endtimeOut) and (strlen($str) < 515) and !feof($c)) {
                   
sleep(1);  // Note: This may require tuning
                   
$str.= fgets($c515);
                }
               
// Handling first-read timeout
               
if (time() >= $endtimeOut) {
                   
trigger_error('Timeout'E_USER_WARNING);
                    break;
                }
               
stream_set_blocking($ctrue);
            } else {
               
$str fgets($c515);
            }
           
$data.= $str;

           
// Handling of "traditional" timeout
           
$info stream_get_meta_data($c);
            if (
$info['timed_out']) {
                   
trigger_error('Timeout'E_USER_WARNING);
                    break;
            }
        }
?>
2016-01-10 01:06:27
http://php5.kiev.ua/manual/ru/function.stream-set-timeout.html
If the timeout fails, because the server remains completely silent, one may have to add stream_select() to make the timeout work. This may be much more efficient that a non-blocking reading operation.

<?php
stream_set_timeout
($c$timeout);
$data '';
$stR = array($this->smtp_conn);
$stW null;
while (
is_resource($c) && !feof($c)) {
    if (!
stream_select($stR$stW$stW$timeout)) {
       
trigger_error('Timeout');
        break;
    }
   
$str fgets($c515);
   
$data.= $str;

   
// Handling of "traditional" timeout
   
$info stream_get_meta_data($c);
     if (
$info['timed_out']) {
       
trigger_error('Timeout');
        break;
    }
}
?>

Background: We had issues with a SMTP server that was addresses unencrypted while expecting TLS encryption. The stream_set_timeout() alone did not work as expected and the script hung for an hour or more.
2016-01-10 15:15:28
http://php5.kiev.ua/manual/ru/function.stream-set-timeout.html

    Поддержать сайт на родительском проекте КГБ