0

Something seems wrong with my php script, but I have no idea what it is. The only possible thing that seems to be wrong is something to do with the cache, but I am not sure. Here's my script, I'll tell you what's happened below the code:

<?php
set_time_limit(0);
header('Content-Type:text/event-stream');
$prevmod=$lastmod=filemtime('chattext.txt');
function waitformod(){
global $lastmod;
global $prevmod;
while($prevmod==$lastmod){
    usleep(100000);
    clearstatcache();
    $lastmod=filemtime('chattext.txt');
    }
echo 'data:'.file_get_contents('chattext.txt').PHP_EOL.PHP_EOL;
flush();
$prevmod=$lastmod;
}
while(true){
waitformod();
}
?>

This is supposed to be used with the JavaScript EventSource and send the contents of chattext.txt whenever it is modified. The file does not output anything, however. I think it is because of the infinite loop. Is there any way to fix this?

2
  • This happens: 1) I modify the file 2) The php file sends chattext.txt as it was before I modified the file. Does that make more sense? Commented Jul 30, 2012 at 5:12
  • You mean a part from the fact that you are using globals? Commented Jul 30, 2012 at 5:18

1 Answer 1

1

Does something like this work better?

<?php

set_time_limit(0);
header('Content-Type:text/event-stream');

$prevmod = $lastmod = filemtime('chattext.txt');

function waitformod(){
    global $lastmod;
    global $prevmod;

    while($prevmod == $lastmod) {
        usleep(100000);
        clearstatcache();
        $lastmod = filemtime('chattext.txt');
    }

    echo 'data:'.file_get_contents('chattext.txt').PHP_EOL.PHP_EOL;
    flush();

    $prevmod = $lastmod;
}

while(1) {
    waitformod();
}

Your current code looks like it reads the file, outputs it, waits for it to change, and then terminates.

Sign up to request clarification or add additional context in comments.

3 Comments

This seems great! Just asking (it's not important) what does flush() do in this case? I've heard of it but don't know what it does.
It (tries) to force the server to flush the output buffer and send all data to the client at that time. Output is often buffered and doesn't get send immediately.
It looked like this would work, but it doesn't output anything. I think it is the infinite loop. How can I fix this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.