Keep Coding

Never Stop Learning

Continue processing PHP after sending 200 OK response

Recently I’ve come across APIs and mainly event management systems that need to receive a HTTP 200 OK response upon sending a request to our server. For example, if you need to integrate Slack Events API your server has to respond a HTTP 200 OK within 3 seconds to every event it receives. Another example is where your server has to respond an [accepted] response within 10 seconds to Adyen notifications.

Keep the execution after sending HTTP response

In order to handle these situations it’s recommended to keep replying to notifications separated from processing them. Another solution is to first return a successful response and then continue execution of the script in the same process. To achieve this I’ve written the following function:

So assuming you’ve got a function named handleEvent() which is called whenever your server receives a request you can use respondOK() function as follow:

You can find more around this topic here and here.

1 Comment

  1. Any idea why it gets stuck when trying to fetch an API after sending resposneOK()?

    Try something like
    `
    <?php
    $firstHit = file_get_contents($entrypoint);
    error_log('before response: ' . $firstHit);
    resposneOK();

    sleep(1);
    error_log('slept for 1 sec');

    $secondHit = file_get_contents($entrypoint);
    error_log('Second hit: ' . $secondHit);
    die;

Leave a Reply

Your email address will not be published.

*