View Full Version : polling a server to check for a file state change.

02-13-2009, 10:23 AM
I am not sure where to put this question, hopefully here is ok.

I have a web app that needs its clients to poll a server every few seconds to check if a specific file has changed. If the file has changed it sends an alert to the client [a swf gets played] .

My scripts work fine the majority of time and for the majority of users but my method seems to be issuing a phantom alert to some but not all clients at around the time the server switches over to a new day(midnight).

It uses a cookie, which is created on page load to store the last modification date of a file on the server. That cookie value is then later compared with the files' modification date that is returned by a php script called via an ajax request [which is issued every few seconds]. What the file contains is irrelevant as i dont want to bog the server down by opening and reading files every few seconds by maybe 200 clients.

i will include relevant code snippets , [it uses the prototypejs library for issuing ajax requests]

// on page creation
// get file mod time and set cookie lastChange
$value = filemtime('../check/test.txt');
setcookie("lastChange", $value);

function checkChanged() {
new Ajax.Request("check_changed.php", {
method: 'get',
onSuccess: function(transport){ var x = get_cookie ( "lastChange" );
var response = transport.responseText;
if (x != response && response != 0) // cookie != last file modification time or invalid response.
set_cookie ( "lastChange", response );}}});}


if($timeS = filemtime('../check/test.txt'))
{ echo $timeS;}
else echo 0;

Now i believe my issue may be caused by this:


is anyone able to confirm that this is indeed my issue? and if it is what sort of performance hit would i suffer if i put
clearstatcache(); at the beginning of my checkchanged.php script?

i would also like to know if there is any other [more efficient] solutions i could use.. and whether or not the way i have decided to approach this problem is entirely foolhardy?

I welcome any comments at all, as this issue has bugged me persistently since i have embarked on this project and its pretty much critical to its success.


02-14-2009, 10:17 PM
ok i decided to inspect the http response headers of my test.txt.. meaning i dont need no cookies or server side scripts.. surely the most efficient way of checking for that state change. ll include the code.

var LastMod;
function checkChanged() {
new Ajax.Request("http://XXX.com/check/test2.txt", {
onSuccess: function(transport){
var header = transport.getResponseHeader('Last-Modified');
if (LastMod != header && LastMod !=null)
{LastMod = header;swfobject.getObjectById("siren").Play();}
else LastMod = header;

very happy with my solution :)

rnd me
02-15-2009, 08:26 AM
doing a head request instead of GET virtually guarantees a single packet ping, but if the text file is small enough, it shouldn't make a huge difference.