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