1

I have a web service written in PHP to which an iPhone app connects to. When the app calls the service, a series of notification messages are sent to Apple's APNs server so it can then send Push Notifications to other users of the app.

This process can be time consuming in some cases and my app has to wait a long time before getting a response. The response is totally independent of the result of the notification messages being sent to the APNs server.

Therefore, I would like the web service to send the response back to the app regardless of whether the messages to APNs have been sent.

My current code:

<?
    <...>
    echo $chatID; // This has to be printed immediately
    include('apns.php'); // Just invoke this, dont wait for response! 
?>

How do I do this?

Mariusz B.
  • 240
  • 4
  • 15
  • add `flush();` `echo $chatID; // This has to be printed immediately` immediately after this statement before including `include('apns.php');` – swapnilsarwe Jul 26 '12 at 11:07
  • I used this one: http://stackoverflow.com/questions/962915/how-do-i-make-an-asynchronous-get-request-in-php This resolved it! Thank you all. – Mariusz B. Jul 26 '12 at 11:33

2 Answers2

3

You shoud close the connection and then continue processing like this:

set_time_limit(0); 
ignore_user_abort(true);  

//start the output buffer
ob_start();

//process what needs to be returned to browser
echo $chatID;

//tell the browser not to expect any more content and close the connection
header("Content-Length: " . ob_get_length());
header("Connection: close");
ob_end_flush(); 
ob_flush(); 
flush(); 
//continue processing
package
  • 4,741
  • 1
  • 25
  • 35
  • Yeah but `ob_start()` will start output buffering and will not send any output to the browser, except for headers. -1 to you, bro. – package Jul 26 '12 at 12:13
  • why do the ob_start acrobatics then when you could simply do `header(); header(); echo; ob_flush(); flush();`? – Quamis Jul 27 '12 at 08:04
  • Because browser would close connection immediately (ob_get_length() = 0) without getting the desired output. Calculating output length, setting the headers, echoing the output and flushing, gives more acrobatics, IMHO. – package Jul 27 '12 at 09:25
2

Call flush();; this will ensure any data printed earlier is sent to the client immediately. In case you are using output buffering you need to call ob_flush(); first.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636