通过"proxy"服务器进行 PHP 刷新服务器响应


我有一个运行Apache/PHP的

"代理"服务器(A(请求另一个使用file_get_contents运行Apache/PHP的服务器(B(。当用户请求服务器 A 时,它会请求服务器 B。服务器 B 上的请求最多需要两分钟才能完成,因此它会很早就响应,然后是等待动画,然后是 PHP flush() sth。喜欢这个:

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   <---   

我现在遇到的问题是,来自 B 的早期同花顺并没有被 A "镜像"。因此,用户必须等待很长时间才能看到最终响应。当我直接调用服务器 B 时,它会在 1 秒后显示等待动画。

"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);
?>

"b.php"的最小示例代码:

<?php
echo 'Loading...';
flush();
// Long operation
sleep(60);
echo 'Result';
?>

问:有没有办法让服务器 A 从服务器 B "镜像"早期flush,从服务器 B 发送确切的刷新结果?

使用 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);
?>

最新更新