doupinwan0563 2013-10-09 20:34
浏览 74
已采纳

PHP通过“代理”服务器刷新服务器响应

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?

  • 写回答

1条回答 默认 最新

  • douya1248 2013-10-09 20:40
    关注

    use fopen/fread instead file_get_contents. Then you can flush between your reads

    Something like this:

    <?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);
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)