Run PHP script without webpage waiting for it to finish

淺唱寂寞╮ 提交于 2019-12-24 02:44:13

问题


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.

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).

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.

SOLUTION:

This is what worked for me (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

回答1:


  • For PHP-fpm:

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

  • For apache:

    See this link - close a connection early



来源:https://stackoverflow.com/questions/25583413/run-php-script-without-webpage-waiting-for-it-to-finish

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!