make php loop echo content once

i have a php page that checks if a file is on the server and makes it echo Online if the file is found but it does this forever and i only want it to do it once.

<h3 class="monospace sec2">Server status: </h3>
  <?php
  ob_start();
  while(true){
    $filename = '/var/www/html/.online';

    if (file_exists($filename)) {
        echo '<span style="color:#00FF00;text-align:center;">Online</span>';
        ob_end_clean();
    } else {
        echo '<span style="color:#ff0000;text-align:center;">Offline</span>';
        ob_end_clean();
    }
  }
  ?>
</div>

it keeps echoing online and continues to make the page longer i just want it to print once. can you please help me.

1 answer

  • answered 2020-10-30 00:47 Nuno Maduro

    My guess is that you just want to print something when the status of the file changes, so this is the code you are looking for:

    <h3 class="monospace sec2">Server status: </h3>
    <?php
    
    $online = null;
    ob_start();
    
    while (true) {
        $filename = '/var/www/html/.online';
    
        if (file_exists($filename)) {
            if ($online !== true) {
                echo '<span style="color:#00FF00;text-align:center;">Online</span>';
                ob_end_clean();
    
                $online = true;
            }
        } else {
            if ($online !== false) {
                echo '<span style="color:#ff0000;text-align:center;">Offline</span>';
                ob_end_clean();
    
                $online = false;
            }
    
        }
        
        // Please consider introducing a sleep here. No need to check if the file exist every millisecond.
        // sleep(1);
    }
    
    ?>
    </div>