Skip to main content
  • If you’ve ever needed real-time data on the front-end of your website and you were using PHP as your back-end, you are most likely familiar with using a polling technique to fetch data.  What you may not know, however, is that another method exists for pulling data that does not require a large number of unnecessary requests.  Enter Comet…


  • Sounds great right? Just wait for the data to come to you!
  • The problem? Currently, no built in Comet functionality exists for PHP and Javascript.  I’ll share with you my code for implementing a Comet controller.

In this article I’ll provide the functions you need to get this working today on your project.  You will have to make some modifications to fit the framework and structure of your site, but if you need help, just leave a comment and I’ll do my best to get back to you!


How to make a long held http request

Before we delve into code, I’ll give you a short summary of how we are going to accomplish our goals.  We will utilize a file on our system to keep track of if there are any changes we need to “push” to the front-end.  We will then provide a listener to that file so that if there is any change we will exit a loop and return the long held request.

First things first let’s make a “Push” function that modifies a simple text file.  This way any listeners looking at that file will trigger their callbacks.

class Comet {
	static public function push($filename) {
		file_put_contents($filename,"Updated @ ".date('m/d/Y h:i:s'));

We built a class so that we can use this code in a nice clean way.   Calling this is as simple as using:


Now let’s create our listener function.

static public function listen($filename,$timestamp) {
    if (!file_exists($filename)) {
	$lastmodif    = $timestamp ? $timestamp : 0;
	$currentmodif = $this->getPreciseTime($filename);
	while ($currentmodif <= $lastmodif) {
	  $currentmodif = $this->getPreciseTime($filename);
	$response = array();
	$response['msg']       = file_get_contents($filename);
	$response['timestamp'] = $currentmodif;
	echo json_encode($response);

Obviously $filename here will match the filename in the first function and the $timestamp parameter helps us keep track of changes.

The very first part of this function checks if the file exists, if not, it creates the file.

We pull the current time and store into $currentmodif using a special function that pulls a very precise time in PHP.  I will provide this function below.

Next we check if timestamp was sent in, if not, sets it to 0.

The while loop is where the magic of the long held requests happens.  We check if the last modification happened after the current time.  If not, we just do a micro-sleep for 10 ms and try again.   If we do have a new modification we exit the loop and return our new timestamp for modification and a message.

GetPreciseTime Function

private function getPreciseTime($filename) {
    $dateUnix = shell_exec('stat --format "%y" '.$filename);
    $date = explode(".", $dateUnix);
    return filemtime($filename).".".substr($date[1], 0, 8);

That’s it for the back-end, moving onto the front.


Simple Functions for Interaction with Comet Backend

var Comet = function () {
    this.timestamp = 0;
    this.noerror = true;
    this.connect = function(file,callback) {
        var self = this;        
            type : 'post',
            url : '/comet',
            dataType : 'json',
            data : {
                'timestamp' : self.timestamp
            success : function(response) {
                self.timestamp = response.timestamp;
                self.noerror = true;
            complete : function(response) {
                if (!self.noerror) {
                    }, 5000);
                }else {
                self.noerror = false;

Most of this code is self-explanatory so I’ll just point out the workings of the timestamp.  Notice we set timestamp to the value returned from PHP.  The ‘callback’ parameter in the connect function here contains whatever function you want to trigger when something changes.

What’s Missing?

You may have noticed that within this code there is actually nothing to change anything on a database or such.  That’s because that part of the logic is separated out here.  Our goal is to allow many connections or listeners to a single file that will all trigger at the same time on a change.  So the changes can happen in any way you want and you have to hook them up using the PHP push function we made first.  So whenever you want to trigger an update to all listeners, just call that push function in PHP.


Questions, comments? Please leave them below.