3

I am working on php script that may involve a long running task. The process goes like this, a user (in my case case using an iOS application) submits data to my web service. Part of the process requires my php script to contact a third party to verfity some of the submitted data. The client (on the iPad) has no need to wait for the response from the third party.

Pseudocode:

Pull values from _POST[]
some simple validation
if _POST[] values are good
    return success to client
    further process submitted data with thrd party
    update database
else
    return error code and message

How would it be possible to return a simple JSON object from my server only to act as receipt, and have my php script further process the submitted data. The third party I am using has been known to be slow to respond (makes several hops, and has been known to take several minutes for a response).

Mike D
  • 4,938
  • 6
  • 43
  • 99

1 Answers1

6

While you can send the output buffer early and keep processing (see Continue processing after closing connection) it's a hacky solution and not suited to PHPs request life-cycle.

A better method is to create a processing queue. When the client hits your service, you return the success status and insert a processing request in the queue (for example, in a database table / key-value store, etc). A separate process (e.g. cron job running a CLI script) picks up the tasks and executes them first in first out. This allows long running scripts to execute out of band - perhaps even on a different server.

As an aside, this also allows you to free up the web server for more requests even if the client needs to check on the result of the long running process. The client can poll the server to check if the job is complete, and get the full response when it's ready.

Community
  • 1
  • 1
Hamish
  • 22,860
  • 8
  • 53
  • 67