【问题标题】:make php loop echo content once使php循环回显内容一次
【发布时间】:2020-10-29 22:11:50
【问题描述】:

我有一个 php 页面,它检查文件是否在服务器上,如果找到该文件,则使其在线回显,但它会永远执行此操作,我只希望它执行一次。

<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>

它一直在网上回响并继续使页面变长我只想打印一次。你能帮帮我吗?

【问题讨论】:

  • 去掉while循环

标签: php html linux


【解决方案1】:

我猜你只是想在文件状态改变时打印一些东西,所以这是你要找的代码:

<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>

【讨论】:

    猜你喜欢
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多