php是循环执行的吗?

我需要删除 filename.html(如果存在),创建一个新的 filename.html 并显示它,但我有以下问题。当创建一个新的 filename.html 时,它会立即被终止,就像 php 重新开始一样。有没有办法执行一次?这是我的 php.ini。


<?php


  $filename = 'filename.html';


  if (file_exists($filename)) {       // if filename.html exist i delete it

     unlink($filename);

  }


  do {

    if (file_exists($filename)) {    // waiting for a new filename.html (generated by another process)

         include ($filename);        // i will show it when ready

         break;

    }

  } while(true);


?>

我也尝试过此解决方法仅在开始时执行删除,但它不起作用:


if( !defined('ALREADYEXECUTED') ){       

  if (file_exists($filename)) {

     unlink($filename);

  }

}

define('ALREADYEXECUTED', TRUE);


米琪卡哇伊
浏览 77回答 3
3回答

慕后森

header("Refresh:2") 的测试对我不起作用,但它帮助我找到了解决方案(肯定有更好的解决方案):我不得不将 php 分成 2 部分:首先:<?php&nbsp; $filename = 'filename.html';&nbsp; if (file_exists($filename)) {&nbsp; &nbsp; &nbsp; &nbsp;// if filename.html exist i delete it&nbsp; &nbsp; &nbsp;unlink($filename);&nbsp; }&nbsp; header('Location:secondfile.php');}第二个文件是这样的:&nbsp; <?php&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; $filename = 'filename.html';&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; do {&nbsp; &nbsp; &nbsp; &nbsp; if (file_exists($filename)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; usleep( 100000 );&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; include ($filename);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; } while(true);&nbsp; ?>回答一些问题: $filename 在几毫秒内创建。之前创建的文件被删除,在这种情况下不会再被删除。我不是 php 专家,如果有更好的解决方案在一个文件中完成它,我会很高兴学习。

慕娘9325324

您在代码中使用了无限循环,这对于您要做的事情来说不是最佳实践!您可以使用header("Refresh:1")刷新页面来每秒检查文件是否存在。这可以节省你的资源,也可以做你想做的事。<?phpheader("Refresh:2");$filename = 'filename.html';if (file_exists($filename)) { // if filename.html exist i delete it&nbsp; &nbsp; unlink($filename);}if (file_exists($filename)) { // waiting for a new filename.html (generated by another process)&nbsp; &nbsp; include ($filename); // i will show it when ready}?>包含新文件后要小心删除header("Refresh:2"),或使用条件来避免包含后删除。

波斯汪

只需摆脱 do while 循环,这就是导致无限循环的原因。那本来的目的是什么?
打开App,查看更多内容
随时随地看视频慕课网APP