HTTP long poll example in php ajax 4

[icon name=”paper-plane” class=”” unprefixed_class=””] UPDATED: A better and easier way to do this is via Server Sent Events, Check out my recent post.

Simple and easy PHP example of how to integrate long-polling (“hanging GET”) to simulate server PUSH and add more dynamic content to your web pages. As a standard HTTP is terrific protocol likely the most popular protocol ever (since it’s the foundation of the modern web portion of the Internet), but even so its mostly a REQUEST/RESPONSE protocol, there’s limited ability for the server to “push’ requests to the client, and there are many instances where this feature would be useful (streaming stock information, real-time server status views, real time alerts of all types). Of course having the server push and keep tracking of thousands or hundreds of thousands of clients can get onerous, which is one reason for the protocols original design.

Because there are many useful situations where server push is beneficial there are several approaches, the general term for these web-based protocols is collectively called Comet (programming).  Most early pre-ajax schemes rely on plug-in technologies, such as Adoble Flash, or Java applets to provide this capability. Because these pug-ins in essence use additional communications channels they can setup all sorts of flexible communication standards.

I have a more recent post on webSockets which are a more modern way to do this

Enter HTTP Long-Poll

One technique that can be used to “simulate” server push, is by using HTTP long-polling (sometimes referred to as hanging GET’s), is the process of making use of the features of the the HTTP a keep-alive-mechanism. By making am $.ajax  request to the server and setting the HTTP /1.1 timeout value to a very long time-frame  the browser can monitor the XHR channel for periodic requests and respond to those request. Below is a simple example of how long-polling can be done using this mechanism.

To prevent overwhelming the server by requesting multiple long connections to stay open , consider using a node.js server to respond in a more efficient way to the long-poll request. In a follow up to this post I will add a node.js sample.

There are of course a few caveats:

  • First and foremost, you can quickly overwhelm a traditional Apache web server by requesting so many connections to remain open, in fact most web servers have hard limits for example MaxClients parameter in httpd.conf file sets the max limit of connections for apache server. The default connection limit is 256. So to not DDOS your own server beware of this restriction.
  • Again in a situation where you’re dealing with thousands of clients, aside form the aforementioned connection limit you also will incur increased bandwidth demands, particularly if your application is doing lots of pseudo-streaming type traffic.
  • Also its not suited for true streaming, such as video or audio streaming. Because HTTP still operates over TCP high-bandwidth applications that require true UDP-level streaming capabilities will not function well with this method.

    Sample PHP long-polling code (Server side)

  • Keeping our example simple, we first create the Server part (a php script) checks a simple text file changes, and if t detects them is flushes t’s buffer to the awaiting long-polling browser.
<?php
$filename= dirname(__FILE__)."/data.txt";
$lastmodif = isset( $_GET['timestamp'])? $_GET['timestamp']: 0 ;
$currentmodif=filemtime($filename);

while ($currentmodif <= $lastmodif) {
usleep(10000);
clearstatcache();
$currentmodif =filemtime($filename);
}

$response = array();
$response['msg'] =Date("h:i:s")." ".file_get_contents($filename);
$response['timestamp']= $currentmodif;
echo json_encode($response);

?>
  • The script above simply replays the contents of the data.txt file to the browser. This is only done to simplify this example for demonstration purposes. Needless to say there are inherent security risks in just spitting out a server file verbatim, but the server file can easily be replaced by a more secure stream of one kind or another. This method makes  it easy to dump status updates to a flat text file and have them  “pushed” to  the browser as they are written to the file.To see it in action manually or automatically change this file and re-save it, and watch it appear the browser.
  • HTML long-polling code (Client side)

    The .ajax making use of Jquery is is below:

    <html>
    <head>
    <title>Long Poll Example</title>
    <script src="jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript" charset="utf-8">
    var timestamp=null;
    function waitForMsg(){
    $.ajax({
    type: "GET",
    url: "getdata.php?timestamp="+timestamp,
    async: true,
    cache: false,
    
    success: function(data){
    var json=eval('('+data+ ')');
    if (json['msg'] !="") {
    //alert( json['msg'] );
    //Display message here
    
    $("#msgold").empty();
    $("#msgold").append(json['msg'] +"<hr>").slideDown("slow");
    
    }
    timestamp =json["timestamp"];
    setTimeout("waitForMsg()",1000);
    },
    error: function(XMLHttpRequest,textStatus,errorThrown) {
    // alert("error: "+textStatus + " "+ errorThrown );
    setTimeout("waitForMsg()",15000);
    }
    });
    }
    
    $(document).ready(
    function()
    {
    waitForMsg();
    });
    </script>
    </head><body>
    <H3> Server Results </H3>
    <hr />
    <div id="messages"><div id="msgold"></div></div>
    <A href='stream.html'>Another streaming Example Stream.html </a>
    </body>
    </html>

    Download the long poll script here.
    See the running long-poll script here: The data.txt is a file that contains links to various web sources and is updated once a day (so changes “server push” may not be so obvious).

    Future of server push is Websockets and Server-side events

    Websocket and to a degree server-side events is the likely successor of long-polling and other HTTP server push solutions (Flash, java applets . It has been designed from the ground up to provide full-duplex communications channels over a single TCP connection. It’s been standardized by the W3C and other governing bodies and will likely form the foundation for future full-duplex communications between user-agents and servers.

  • You can see good example of Websockets at work  here. Keep in mind this should work with most modern post  IE9+ and other browsers.
  •  So the future is bright, but in the meantime to offer support for the wides range of browsers feel free to implement the method above.
  • Share  your thoughts below.

4 thoughts on “HTTP long poll example in php ajax

  1. Pingback: Understanding Ajax Long-Polling Requests - WebCooker

  2. Reply Bruno Fabricio Cassiamani Aug 17,2015 7:22 am

    Hello!

    Congratulations on your example, very well, but i would like know of how make the connection long polling with Mysql.

    • Reply Christopher J. Joy Dec 22,2017 10:14 am

      I’m generating one now that uses MySQL. The way I’m doing it is my requesting page send the time of the last request received. The server-side php queries the MySQL DB for all records that have Received_Time > Last_Update_Time. If the query is empty, it sleeps for a minute and tries again. If the query has results, it echoes the results.

Leave a Reply