Skip to content

Instantly share code, notes, and snippets.

@jonathantneal
Created March 28, 2014 23:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathantneal/9844792 to your computer and use it in GitHub Desktop.
Save jonathantneal/9844792 to your computer and use it in GitHub Desktop.
Simple longpoll functionality between JavaScript and PHP
function longpoll(src, onload, onerror) {
// create modified header
var ifModifiedSince;
// create request
function onrequest() {
var xhr = new XMLHttpRequest();
xhr.open('GET', src);
// attach modified header
xhr.setRequestHeader('If-Modified-Since', ifModifiedSince);
// on request changes
xhr.onreadystatechange = function () {
// check if request finished
if (xhr.readyState === 4 && xhr.status) {
// if status returns error, goto error
if (/^[45]/.test(xhr.status)) xhr.onerror();
else {
// conditionally run load callback
if (typeof onload === 'function') onload.call(xhr, xhr.responseText);
// update modified header
ifModifiedSince = xhr.getResponseHeader('Last-Modified');
// repeat request
onrequest();
}
}
};
// on request errors
xhr.onerror = function () {
// conditionally run error callback
if (typeof onerror === 'function') onerror.call(xhr, xhr.statusText);
};
// initiate request
xhr.send(null);
}
// run request
onrequest();
}
<?php
$SRC = 'test.json'; // path to file
$DELAY = 20; // measured in milliseconds (1000 = 1 second)
$TIMEOUT = INF; // measured in milliseconds, infinite will never timeout
$MIME = 'text/plain; charset=utf-8'; // mime type and charset
// set indefinite execution time for this script
set_time_limit(0);
// get modified header as time
$IF_MODIFIED_SINCE = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
while (true) {
// clear file status cache (allow multiple checks on the same file)
clearstatcache();
// get file modified time
$LAST_MODIFIED = filemtime($SRC);
// if modified times do not match or timeout expires
if ($LAST_MODIFIED !== $IF_MODIFIED_SINCE || !$TIMEOUT) {
// set cache headers to not cache
header('Cache-Control: private, max-age=0, no-cache');
// set mime type
header('Content-Type: '.$MIME);
// set updated modified header
header('Last-Modified: '.gmdate('D, d M Y H:i:s T', $LAST_MODIFIED));
// print the response
print(file_get_contents($SRC));
// end
break;
}
// otherwise
else {
// reduce timeout by delay
$TIMEOUT -= $DELAY;
// wait for delay
usleep($DELAY * 1000);
// repeat
continue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment