0

I need to develop HTTP push using php, it sends back a message to the browser every 20 seconds.. that i need to display on the server

Is there any way of implementing http push in php with out using any sockets or library?

  • I need to develop HTTP push using php, it sends back a message to the browser every 20 seconds.. that i need to display on the server. – user1234077 Feb 26 '12 at 17:07
  • As Andrew suggested, below, polling from JavaScript is generally a much better solution than leaving a push running, tying up an Apache connection. Check out [Comet](http://en.wikipedia.org/wiki/Comet_%28programming%29). – ghoti Feb 27 '12 at 12:40

2 Answers2

3

Sure: don't let your PHP script terminate for as long as you want the connection to remain open. Since you are generating output every 20 sec, the connection is much less likely to timeout.

There are many ways to achieve this including blocking (e.g. sleep() below) or busy waiting, but the simplest solution would be:

while( true ){
    generate_output();
    sleep(20);
}

You may need to handle unexpected connection termination on the client-side, but this is the jist of it. Check your system configuration to see how many open connections you can handle. (In Apache, see MaxClients)

As for the client-side, see this answer https://stackoverflow.com/a/7953033/329062

Community
  • 1
  • 1
Greg
  • 12,119
  • 5
  • 32
  • 34
1

The only way to do this is to use WebSockets, "Long Polling", or an AJAX request every 20 seconds (even if there is nothing to update). Your solution will depend on which browsers you want to support. For example, newer browsers support Web Sockets, but older browsers don't. I would recommend researching Web Sockets. They are a great solution for this type of situation.

Andrew
  • 227,796
  • 193
  • 515
  • 708