运行没有网页的PHP脚本等待它完成 [英] Run PHP script without webpage waiting for it to finish

查看:77
本文介绍了运行没有网页的PHP脚本等待它完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些基本的网站跟踪软件,可以从网页跨域发送带有 jQuery AJAX JSON对象到一个服务器,其中数据由 php 脚本处理。这是在 window.onbeforeunload 上触发的。

I have some basic website tracking software that sends a JSON object with jQuery AJAX from a webpage cross-domain to a server where the data is processed by a php script. This is triggered on window.onbeforeunload.

在对我的 php 脚本进行基准测试时,我意识到不同域上的客户端网站仍在等待php脚本在加载下一页之前完成运行。例如,客户端站点的访问者导航到另一个页面。我们将 JSON对象跨域发送到服务器进行处理。如果我将 sleep(30); 添加到我的 php 脚本,客户端网站将不会加载下一页,直到此 php 脚本完成(30+秒)。

When benchmarking my php script I have realised that the client website on a different domain is still waiting for the php script to finish running before loading the next page. For example, a visitor to a client site navigates to another page. We send the JSON object cross domain to the server to process it. If I add sleep(30); to my php script the client website will not load the next page until this php script finishes (30+ seconds).

运行此脚本后我不需要返回任何值,这样我怎么能确保这个 php 脚本运行而不运行对客户网站有任何影响吗?

I do not need to return any values after running this script so how can I ensure this php script runs without having any impact on the client site?

我希望我已经解释得很好。如果我没有,请问任何问题,谢谢。

I hope I've explained myself well enough. Ask any questions if I haven't, thanks.

解决方案:

这对我有用( http://php.net/manual/en/features.connection-handling.php#93441 ):

ob_end_clean();
header("Connection: close\r\n");
header("Content-Encoding: none\r\n");
ignore_user_abort(true); // optional
ob_start();
echo ('Text user will see');
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush();     // Strange behaviour, will not work
flush();            // Unless both are called !
ob_end_clean();

//do processing here
sleep(5);

echo('Text user will never see');
//do some processing


推荐答案


  • 对于PHP-fpm:

    关闭与客户端的连接(发送响应),但继续运行脚本和处理一些数据,这个功能可以帮助你 - fastcgi_finish_request

    To close connection with client (send response), but continue running script and processing some data, this function can help you - fastcgi_finish_request

    对于apache

    查看此链接 - 提前关闭连接

    这篇关于运行没有网页的PHP脚本等待它完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆