I implemented this using jquery (.ajax) and php (json).
The flow is essentially as follows:
- user calls an html page on their browser
- html page contains an initial jquery .ajax call to a remote php script on the server that performs the required function, in this case, retrieving a few of the last lines of the file being 'tailed'
- if no new lines are available, the php script just loops (wile the ajax caller waits, ie longpolling), and can be configured to time out if necessary (returning an appropriate value back to the ajax calling function on the client)
- when new lines are detected by the php script, they are wrapped in a json response and sent back to the ajax calling function on the browser, which then appends it to the existing content of the page.
- The javascript function will then recursively make the same ajax call, effectively sitting in an infinite loop.
In my specific implementation, i did the following:
- both the ajax call on the client AND the php script on the server have timeouts to handle, for example, broken connections nicely. Also ensures the ajax call does not wait forever.
- the ajax call passes a line number as a reference back to the server to tell it what the last line number was that it received, so the server knows which lines to return. Initially the value is zero, and the server will immediately return the last 10 lines of the file
- when the php script is called, it uses the clients last line number to do a quick check on the file; if new lines have already been added it returns them immediately, if not it sits in a loop (1 second) and then instead checks the files ctime (or mtime) to detect when new lines are written. This is more effective than counting the lines in the file (which could be huge) every second.
See my longpolling/realtime tail implementation using jquery and php here:
https://github.com/richardvk/web_file_tail