PHP thread timeout if no data is transferred

I am currently implementing a PHP class that retrieves image files and caches them locally. These images can come from other local sources through HTTP or through HTTP using the Guzzle client. With PHP stream fairing, I should be able to handle all sources the same way.

What I'm trying to do now ist to implement a timeout if no data is transferred through the stream. This should handle the following cases:

  • The stream cannot be installed in the first place. This should probably be handled on a call fopen, not a timeout.
  • The stream is installed, but no data is being transmitted.
  • The stream is established, data is transmitted, but during transmission it stops for a while.

I think I can do all this with the help stream_set_timeout, but I don’t quite understand what it actually does. Is a timeout used if any operation in the stream takes longer than allowed, i.e. Can I do something that takes 0.5 s twice with a timeout of 0.75 s? Or does this only apply if the data has not been transmitted through the stream for longer than the allowable time?

I tried to test the behavior with this short script:

<?php

$in = fopen('https://reqres.in/api/users?delay=5', 'r');
$out = fopen('out', 'w');

stream_set_timeout($in, 1);
stream_copy_to_stream($in, $out);

var_dump(stream_get_meta_data($in)['timed_out']);

Although the response from is reqres.indelayed by 5 s, I always get falsewith a timeout of 1 s. Can someone explain this?

+4
source share
2 answers

file_get_contents file_put_contents , , , , fopen. , . , , :)

, fopen http ( , ) . GET ( ), fopen, , HTTP- , . , stream_set_timeout , fopen.

, , fopen; fopen . , stream_context_create ( Sammitch) fopen . , script :

<?php

$ctx = stream_context_create(['http' => [
        'timeout' => 1.0,
]]);

$in = fopen('https://reqres.in/api/users?delay=5', 'r', false, $ctx);
$out = STDOUT;

stream_copy_to_stream($in, $out);
var_dump(stream_get_meta_data($in)['timed_out']);
fclose($in);

. , stdout "out", (Darwin). script, .

1, fopen. , .

  • . , fopen, -.

, - ( ..), fopen . script - , . , , fopen false. , false .

  1. , .

, script URL. fopen false ().

  1. , , .

. , script, Content-Length , , ..:

<?php
header('Content-Type: text/plain');
header('Content-Length: 10');
echo "hi";
ob_flush();
sleep(10);

ob_flush PHP ( ) script. , php -S localhost:port, script localhost:port. script , fopen timed_out , true.

stream_set_timeout HTTP GET- fopen , fopen , , . fopen , .

+5

" " .

- - ( TCP-). - - . 20 , .

( ) 5 - , , ( DNS, ..), .

+2

Source: https://habr.com/ru/post/1694303/


All Articles