Ajax Long Polling with PHP

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.

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 in 2017. However, many websites such as facebook, messenger use long polling. Let's discuss about long-polling.

These are to be discussed.

Introduction

Following image describes the concept of Long-Polling.

Explained...

Write the JS code!

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();



The back-end

This is the most important part of the tutorial. Before coding the script, you must know some tricks.

The Infinite Loop



<?php

while(true) {

	echo 'yes'; // this will be executed unlimited times

}



End the execution of the infinite loop when a condition is true

In the script below, we have mentioned 3 different ways to break the loop. Choose the best one by according to your needs. If you are not sure what to you should use, feel free to comment below.



<?php

while(true) {
	
	// escape from the infinite loop
	break; 

	// escape from multiple loops
	for ($i = 0; $i < 10000; $i++) {
		if ($foundAnUpdate) {
			break 2; // escapes from current loop & the infinite loop
		}
	}

	// completely finish the execution of full page
	if ($foundAnUpdate) {
		exit(json_encode[
			'status' => 'success'
	]); // echoes json encoded string & finishes the execution
	}

}


Some useful functions



<?php

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


while(true) {
	
	// here goes the loop

	sleep(1);

}



Step by Step...

Example

Let's see an example using long polling. Here we create a simple notification system with long polling. Consider that we have another php script to update file.txt and saves the latest notification id in the file. The long polling script loop until the file's notification number is larger than last sent notification id to the client-side.



<?php

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);

}



Above example is a simple example of long polling. You can improve your script and even create a huge notification system like facebook, messenger have. Everything is just based on above concepts. If you have any question on this topic feel free to comment below or contact us through twitter.

Comments (0)

POST
Author Supun Kavinda
115 1