1

I have a "proxy" server (A) running Apache/PHP requesting another server (B) running Apache/PHP using file_get_contents. When a user requests server A it requests server B. The request at server B needs up to two minutes to complete, so it responds very early with a waiting animation followed by a PHP flush(), sth. like this:

User       --->   Server A (a.php)             --->   Server B (b.php)
                  - file_get_contents to B            - flush after 1s
                  - nothing happens after 1s          - response end after 2m 
waits 2m   <---   

The problem I have now is that this early flush from B is not "mirrored" by A. So the user has to wait the full time before seeing the final response. When I call server B directly it shows the waiting animation after 1 second.

Minimal example code for "a.php":

<?php
$stream_context = stream_context_create(array(
    'http' => array(
        'method' => 'POST',
        'header' => 'Content-type: application/x-www-form-urlencoded'
    )
));

echo file_get_contents('http://1.2.3.4/b.php', false, $stream_context);
?>

Minimal example code for "b.php":

<?php
echo 'Loading...';
flush();

// Long operation
sleep(60);

echo 'Result';
?>

Q: Is there a way to get server A to "mirror" the early flush from server B, sending the exact flushed result from server B?

4

1 回答 1

1

使用 fopen/fread 代替 file_get_contents。然后你可以在你的读取之间刷新

像这样的东西:

<?php
$stream_context = stream_context_create(array(
    'http' => array(
        'method' => 'POST',
        'header' => 'Content-type: application/x-www-form-urlencoded'
    )
));

$fp = fopen('http://1.2.3.4/b.php', 'r', false, $context);
while (!feof($fp)) {
  echo fread($fp, 8192);
  flush();
}
fclose($fp);

?>
于 2013-10-09T20:40:25.460 回答