是否有一种不那么丑陋的方式来做到这一点:
ignore_user_abort(true);
set_time_limit(0);
ob_start();
echo $response; // send the response
header('Connection: close');
header('Content-Length: '.ob_get_length());
ob_end_flush();
ob_flush();
flush();
在Laravel?基本上我需要服务器在运行事件之前向用户返回响应,我不能使用队列来执行此操作,因为有很多事情要做,而且很多客户端同时执行此操作并且需要完成这些操作立刻,所以他们不能一个接一个地执行。这些事件包括发送邮件,提醒,更新网站表格上的数据等。
在我创建跟踪像素的项目中,我有类似的需求。我想立即回复他们,然后Laravel继续运行。我把这作为index.php
的第一件事:
if($_SERVER['REQUEST_URI'] == '/pixel'){
require "pixel.php";
}
然后在该文件中(其中一些可能与您无关,我需要确保它们没有缓存它以便继续加载像素:
ignore_user_abort(true);
// turn off gzip compression
if ( function_exists( 'apache_setenv' ) ) {
apache_setenv( 'no-gzip', 1 );
}
ini_set('zlib.output_compression', 0);
// turn on output buffering if necessary
if (ob_get_level() == 0) {
ob_start();
}
// removing any content encoding like gzip etc.
header('Content-encoding: none', true);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo ' ';
} else {
header("Content-type: image/gif");
header("Content-Length: 42");
header("Cache-Control: private, no-cache, no-cache=Set-Cookie, proxy-revalidate");
header("Expires: Wed, 11 Jan 2000 12:59:00 GMT");
header("Last-Modified: Wed, 11 Jan 2006 12:59:00 GMT");
header("Pragma: no-cache");
echo sprintf('%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%',71,73,70,56,57,97,1,0,1,0,128,255,0,192,192,192,0,0,0,33,249,4,1,0,0,0,0,44,0,0,0,0,1,0,1,0,0,2,2,68,1,0,59);
}
// flush all output buffers. No reason to make the user wait for OWA.
ob_flush();
flush();
ob_end_flush();
而已。现在,Laravel继续运行,但用户的浏览器已经结束了它的请求。所以我在/pixel
添加了一条正常的路线并完成了我需要做的所有事情(添加到数据库,火灾事件等)。