我正试图将1x1像素的图像推送给我的用户,并在事后在服务器上进行一些其他操作。但是,在该脚本中完成所有操作之前,连接不会关闭。
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);
//check to ses if request is a POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// the GIF should not be POSTed to, so do nothing...
echo ' ';
} else {
// return 1x1 pixel transparent gif
header("Content-type: image/gif");
// needed to avoid cache time on browser side
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.
ob_flush();
flush();
ob_end_flush();
// How can I close the connection to client and do some long operations here. exit() wont work.
// client continues to load image, spinning status.
super_long_function("30 second script");
// client gets success
正如评论所提到的,你需要运行另一个脚本,但仅仅调用exec是不行的。你需要做这样的事情:
exec( 'bash -c "exec nohup setsid *ENTER COMMAND* > /dev/null 2>&1 &"' );
这将在后台运行一个脚本,并允许您的脚本关闭。只要使用exec,就会在PHP中运行一个脚本,并等待它完成。你想要类似的东西:
exec( 'bash -c "exec nohup setsid php LongExecScript.php > /dev/null 2>&1 &"' );
或者,您可以保存他们的数据并使用cron吗?最佳选项IMO.
未经测试,这可能会奏效(免责声明您可能需要调整某些部件)。
<?php
ob_start();
header('Connection: close');
header("Content-Length: 0");
ob_end_flush();
ob_flush();
flush();
// to flush the session to disk if not needed anymore
if (session_id())
session_write_close();
?>
请记住,如果HTTP客户端忽略HTTP 1.1连接:关闭标头,这将不起作用