Search code examples
phpcurlpthreadsslim-3

Run a function after returning response


I have an API created with Slim 3.

In it I have some curl execution such as sending Push notification to a user.

I want send response to requester then execute curl or any other function.

I read about Threads in PHP and use pthreads-polyfill but it sends response after finishing Thread.

Sample tested code:

 $app->get('/test', function (Request $request, Response $response) {
    PushController::publish("1111111", "HELLO");
    $result =  'OK';

    return $response->getBody()->write($result)->withStatus(200);
});

Solution

  • I understand what you are trying to do, and threading is not the answer. One solution is to call a script from the main one, as you mentioned. A more elegant one imho, is to call fastcgi_finish_request . It will return the answer to the requester and continue to execute the script. Unfortunately this function is only available with PHP-FPM. Which is the industry standard by now but does not necessarily comes as default when you install a LAMP stack.