PHP - 等待文件存在

zed*_*dex 6 php while-loop wait

我想执行一个生成 txt 文件的 exe 文件,并在另一个脚本中执行,然后检查 txt 文件是否已创建。

在 xampp 中,我只是将 test.txt 文件拖入以下 php 脚本目录,但它似乎无法正常工作,如果我将 text.txt 添加到目录并启动脚本,而不是在添加之前启动那么第二个回声似乎永远不会发生。

如何让 PHP 等待文本文件存在然后继续?

set_time_limit(0);

echo "Script began: " . date("d-m-Y h:i:s") . "<br>";

$status = file_exists("test.txt");
while($status != true) {
    if ($status == true) {
        echo "The file was found: " . date("d-m-Y h:i:s") . "<br>";
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

这也不起作用:

set_time_limit(0);

echo "Script began: " . date("d-m-Y h:i:s") . "<br>";

while(!file_exists("test.txt")) {
    if (file_exists("test.txt")) {
        echo "The file was found: " . date("d-m-Y h:i:s") . "<br>";
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

has*_*san 5

这应该可以正常工作

set_time_limit(0);

echo "Script began: " . date("d-m-Y h:i:s") . "<br>";

do {
    if (file_exists("test.txt")) {
        echo "The file was found: " . date("d-m-Y h:i:s") . "<br>";
        break;
    }
} while(true);
Run Code Online (Sandbox Code Playgroud)


Man*_*ngo 5

我相信您有其他保护措施可以确保您不会陷入无限循环。

while(!file_exists('test.txt'));
echo "The file was found: " . date("d-m-Y h:i:s") . "<br>";
Run Code Online (Sandbox Code Playgroud)

会更简单。

无论如何,您的问题在于您的预测试。因为它没有开始,所以它永远不会重复。你需要的是一个后测试:

do {
    if (file_exists("test.txt")) {
        echo "The file was found: " . date("d-m-Y h:i:s") . "<br>";
        break;
    }
} while(!file_exists("test.txt"));
Run Code Online (Sandbox Code Playgroud)