Advanced PHP: Ajax Long Polling with PHP


#1

Hi Everyone,

Have you ever wondered how does facebook, messenger, twitter work in real time? Do you like to create your own real time system? :thinking: Then, this tutorial will help you. :wink:

Before we start, I would like to say this is an alias tutorial of the following tutorial I wrote to hyvor developer site. Visit it to see the full tutorial. Here you will learn how to integrate it on 000webhost.
https://developer.hyvor.com/php/ajax-long-polling

Long Polling

Need to create a real time application with javascript and PHP? Actually, there’re some different ways to client-side to interact with the server in real time.

  • Short-Polling
  • Long-Polling
  • Web Sockets
  • Server Sent Events (SSE)

What should I use between them? Not Short Polling or SSE. You may use Long-Polling or Web Sockets. Long-Polling is supported by many browsers (Even IE 8). Web Socket is introduced in HTML 5. So, old browsers do not support it. What is more effective? Long-Polling or Web sockets? It would be the hardest question ever. However, many websites such as facebook, messenger use long polling.

The best part is, you can host your long polling script at 000webhost, but not your web socket scripts :wink:

  • First we send an ajax request from the browser (using javascript) to the web server.
  • Web server loops until it finds an update.
  • Server stops looping and sends the response to the browser
  • Javascript catches the response and updates the DOM.
  • Everything works asynchronously in real time.

Writing JS

First we have to send an ajax request from the browser to the server to accomplish our target. Here we use pure Javascript (Vanilla JS) and haven’t use any library because nowadays, different developers use different libraries. But, almost everyone know pure/vanilla JS. However it doesn’t matter if you use your preferred library to do the same work.

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
	if (this.readyState == 4 && this.status == 200) {
	 	// when everything goes fine...
	}
};
xhttp.open("GET", "long-polling.php", true);
xhttp.send();
  • This is no more than a simple ajax request
  • First we initiate new XMLHttpRequest and save the instance in variable xhttp .
  • Then, we define the onreadystatechange function. This will be executed each time the ready state of the ajax request is changed.
  • Next we open the request. I have use GET method. Also I prefer to use that because it is fast and works fine with long-polling. Mind not to send sensitive data with the request.
    long-polling.php is the file we are going to create in the next step.
  • Finally send the request to the server.

Server Side

PHP makes the work really easier. You just have to use some functions to achieve your targets. To learn about functions that are useful with long polling visit the link I have mentioned at the top. :wink:

In long polling, php loops until it finds an update. Following code will show you how to use it.

include_once 'db.php'; // includes db.php and defines $mysqli variable (Here we use OOP mysqli)

session_write_close();
ignore_user_abort(true);
set_time_limit(0);

$result = $mysqli -> query('SELECT lastNotification FROM notifications WHERE user = 1 LIMIT 1');
$lastNotification = $result -> fetch_object() -> lastNotification;

while(true) {
	
	$data = file_get_contents('file.txt');
	// file.txt saves the 

	if ((int) $data > $lastNotification) {
		exit(json_encode([
			'status' => 'up',
			'id' => $lastNotification
		]));
	}

	sleep(1);

}

Note: You can not use set_time_limit function at 000webhost

In this way you can develop a huge real time web based application. Just use your will-power. :wink:

Thanks.

Supun Kavinda,
Moderator,
000webhost.