HYVOR DEVELOPER
PHP
Feb 6, 2018 6 min 397

Ajax Long Polling with PHP

Need to create a real time application with javascript and PHP? Actually, there's 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 does 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. Let's discuss about long-polling.

These are to be discussed.

Introduction

Following image describes the concept of Long-Polling.

Explained...

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



  • This is no more than a simple ajax request
  • First we initiate new XMLHttpRequest and saves 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 going to create in the next step.
  • Finally send the request to the server.
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

}



  • This is the basic concept of long-polling.
  • It loops while true is true. That means forever!
  • Do not try this in your browser

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

  • session_write_close
  • ignore_user_abort
  • set_time_limit
  • sleep / usleep
  • Session data can't be used in long polling. If you do, it will crash the browser other requests won't load. To cancel usage of sessions we have to use session_write_close() function at the top of the script.
  • ignore_user_abort() function can be used to define whether you need to stop the script when browser request aborted or not.
  • set_time_limit() function can set the max execution time. If the parameter is zero, the script runs forever.
  • sleep() and usleep() functions are very useful and can be used to make the server asleep for a while to make sure that the loop does not affect server's performances.


<?php

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


while(true) {
	
	// here goes the loop

	sleep(1);

}



Step by Step...

  • First we cancel session writing on the script with session_write_close().
  • Then ignore_user_abort(true) makes the script aborted when browser cancel the request. Set it to false if you need to run the script even the browser cancel the request.
  • set_time_limit(0) sets execution time to infinite. But, if lot of users use your website, set it to 30-40 seconds. Otherwise it will overload the server.
  • It's a really good practice to use sleep(1) function. It make the execution delayed for 1 second. usleep() function is also there. There you can set the parameter in milliseconds.
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 latest notification number (id)

	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.

Author SupunKavinda