Php – continue processing php after sending http response

httpPHPresponse

My script is called by server. From server I'll receive ID_OF_MESSAGE and TEXT_OF_MESSAGE.

In my script I'll handle incoming text and generate response with params: ANSWER_TO_ID and RESPONSE_MESSAGE.

The problem is that I'm sending response to incomming "ID_OF_MESSAGE", but server which send me message to handle will set his message as delivered to me (It means I can send him response to that ID), after receiving http response 200.

One of solution is to save message to database and make some cron which will be running each minute, but I need to generate response message immediately.

Is there some solution how to send to server http response 200 and than continue executing php script?

Thank you a lot

Best Answer

Yes. You can do this:

ignore_user_abort(true);//not required
set_time_limit(0);

ob_start();
// do initial processing here
echo $response; // send the response
header('Connection: close');
header('Content-Length: '.ob_get_length());
ob_end_flush();
@ob_flush();
flush();
fastcgi_finish_request();//required for PHP-FPM (PHP > 5.3.3)

// now the request is sent to the browser, but the script is still running
// so, you can continue...

die(); //a must especially if set_time_limit=0 is used and the task ends