您的当前位置:首页正文

PHP访问结束如何继续处理

来源:独旅网
今天看到dewen里面有人问,如何用php实现浏览器访问结束后继续执行后续代码,我写了个demo,在php-fpm环境下非常容易实现,fastcgi_finish_request即可。如果是其它容器,我想只能通过输出javascript到客户端实现跳转,然后后台继续执行。

demo如下,php-fpm测试可用,apache php-cgi由于没有环境没有测试。 (推荐学习:PHP视频教程)

<?php
// 你要跳转的url
$url = "http://www.baidu.com/";
 
// 如果使用的是php-fpm
if(function_exists('fastcgi_finish_request')){
 header("Location: $url");
 ob_flush();
 flush();
 fastcgi_finish_request();
// Apache ?
}else{
 header( 'Content-type: text/html; charset=utf-8' );
 if(function_exists('apache_setenv'))apache_setenv('no-gzip', '1');
 ini_set('zlib.output_compression', 0);
 ini_set('implicit_flush', 1);
 echo "<script>location='$url'</script>";
 ob_flush();
 flush();
}
 
 // 这里是模拟你的耗时逻辑
 sleep(2);
 file_put_contents('/tmp/test.log', 'ok');
显示全文