2017-03-26 48 views
0

我想執行一個生成txt文件的exe文件,並在另一個腳本中檢查是否已創建txt文件。PHP - 等待文件存在

在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; 
    } 
} 

這也不起作用:

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; 
    } 
} 
+2

'$ status' __never__改變它的值。 –

+1

*「雖然狀態不正確,如果狀態爲真...」 - - 這個嘗試的邏輯有很多錯誤。 – deceze

+0

我曾試圖改變它是直接的,看到我的編輯,但它仍然無法正常工作,第二個回聲從來沒有發生過。 – zeddex

回答

1

這應該工作正常

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); 
+0

這很好,謝謝 – zeddex

+0

如果你要添加一個sleep(1);那將會直接在if語句後面嗎? – zeddex

+0

是的,你必須在if語句中加上這個 – hassan

2

我想你應該使用這種方法:

set_time_limit(0); 

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

while (true) { 
    // we will always check for file existence at least one time 
    // so if `test.txt` already exists - you will see the message 
    // if not - script will wait until file appears in a folder 
    if (file_exists("test.txt")) { 
     echo "The file was found: " . date("d-m-Y h:i:s") . "<br>"; 
     break; 
    } 
} 
2

我相信你有其他保障措施可以確保你並沒有陷入無限循環。

while(!file_exists('test.txt')); 
echo "The file was found: " . 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(!file_exists("test.txt")); 
+0

謝謝,我通常不會使用while循環,所以我會記下這個。 – zeddex