0

I'm looking for guidance on a question I can barely grasp as is. I have the content of a .txt file loaded through readfile('stories/'.$sessionid.'.txt'); in PHP. Any user can add text to the .txt file through POST, and I would like for other users with that page open to become notified of (and updated to) the recent file change – whilst the user who did the update doesn't receive an notification about his own update.

I've been having a hard time finding relevant information, since I'm not sure about what I should search for – or even method of approach for that matter (jQuery, AJAX, PHP?). I read something about filemtime but I don't know how to apply that in this case. I mainly work with front-end, thus I'm not that experienced with this kind of challenges. I kind of found a solution, but it alerts any file-changes all the time, and could possibly put strain on the server (in worst case senario) I think?

var previous = "";

setInterval(function() {
    var ajax = new XMLHttpRequest();
    ajax.onreadystatechange = function() {
        if (ajax.readyState == 4) {
           if (ajax.responseText != previous) {
              alert("file changed!");
              previous = ajax.responseText;
            }
        }
    };
    ajax.open("POST", "stories/<?php echo($sessionid) ?>.txt", true); //Use POST to avoid caching
    ajax.send();
}, 1000);

Is there a way to work and develop this code or where should I begin to look and work with? I really don't have a clue since I've never done anything like this before. Any pointers towards relevant keywords, methods, or tutorials I can search for and use would be greatly appreciated!

Lenny
  • 446
  • 5
  • 21
  • You can do this, but I'd suggest at this point that you hook up a light database and use a message queue instead of constantly checking a file for updates. My personal recommendation would be Redis, it's lightweight and relatively simple for this kind of task. – spirulence Jan 26 '15 at 03:41

1 Answers1

0

If you are finding a way to let multiple users edit a file in realtime, then you can use web sockets. socket.io is a library that lets you send messages bidirectionally between a server and all the clients connected to it through web sockets.

In your case, once an edit has been made to the txt file, you can broadcast a message to all the connected clients informing them about the change.

Its as simple as socket.broadcast.emit('File Edited'), you can either send the new contents over the socket itself or do an ajax query on receiving this socket message.

surajck
  • 1,186
  • 9
  • 23