douhui1333 2013-02-15 20:34
浏览 69
已采纳

我可以像register_shutdown_function一样使用fastcgi_finish_request()吗?

This simple method for caching dynamic content uses register_shutdown_function() to push the output buffer to a file on disk after exiting the script. However, I'm using PHP-FPM, with which this doesn't work; a 5-second sleep added to the function indeed causes a 5-second delay in executing the script from the browser. A commenter in the PHP docs notes that there's a special function for PHP-FPM users, namely fastcgi_finish_request(). There's not much documentation for this particular function, however.

The point of fastcgi_finish_request() seems to be to flush all data and proceed with other tasks, but what I want to achieve, as would normally work with register_shutdown_function(), is basically to put the contents of the output buffer into a file without the user having to wait for this to finish.

Is there any way to achieve this under PHP-FPM, with fastcgi_finish_request() or another function?

$timeout = 3600; // cache time-out
$file = '/home/example.com/public_html/cache/' . md5($_SERVER['REQUEST_URI']); // unique id for this page
if (file_exists($file) && (filemtime($file) + $timeout) > time()) {
  readfile($file);
  exit();
} else {
  ob_start();
  register_shutdown_function(function () use ($file) {
    // sleep(5);
    $content = ob_get_flush();
    file_put_contents($file, $content);
  });
}
  • 写回答

3条回答 默认 最新

  • douyue3800 2013-02-23 10:33
    关注

    Yes, it's possible to use fastcgi_finish_request for that. You can save this file and see that it works:

    <?php
    
    $timeout = 3600; // cache time-out
    $file = '/home/galymzhan/www/ps/' . md5($_SERVER['REQUEST_URI']); // unique id for this page
    if (file_exists($file) && (filemtime($file) + $timeout) > time()) {
      echo "Got this from cache<br>";
      readfile($file);
      exit();
    } else {
      ob_start();
      echo "Content to be cached<br>";
    
      $content = ob_get_flush();
      fastcgi_finish_request();
      // sleep(5);
    
      file_put_contents($file, $content);
    }
    

    Even if you uncomment the line with sleep(5), you'll see that page still opens instantly because fastcgi_finish_request sends data back to browser and then proceeds with whatever code is written after it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测