2

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
MP_Webby
  • 916
  • 1
  • 11
  • 35

1 Answers1

1
Community
  • 1
  • 1
Vasily
  • 1,858
  • 1
  • 21
  • 34
  • 1
    Thanks, from what I understand this looks like a good solution. However I am getting an error: `Call to undefined function fastcgi_finish_request()`. Any idea why? Thanks. – MP_Webby Aug 30 '14 at 14:55
  • 2
    Probably you are using apache instead of nginx+fpm, i think this function works only for fpm. – Ilia Kondrashov Aug 30 '14 at 14:58
  • 2
    Perhaps this is useful: http://stackoverflow.com/questions/138374/close-a-connection-early – KIKO Software Aug 30 '14 at 15:10
  • Yeah, it's seems you are using apache, so apache haven't analogue of this function, but link which @KIKOSoftware has provided is pretty good. May be it's also a good idea to refactor your JS-script so that it do not wait a response from the server ( make it asynchronous ) – Vasily Aug 30 '14 at 15:40
  • Thanks all and @KIKO Software, that did the trick. Solution and link above. – MP_Webby Aug 30 '14 at 15:58