2013-05-31 52 views
0

代碼:file_exists高負載系統

$tmp_file_path = '/path/to/tmp/file'; 

// move file from tmp dir 
$new_file_path = '/path/to/new/location/file'; 
while(file_exists($new_file_path)){ 
    $new_file_path = $new_file_path . microtime(true); 
    usleep(100000); 
} 

// HERE ANOTHER INSTANCE OF THIS SCRIPT COULD HAVE ALREADY TAKEN NEW NAME, 
// $new_file_path 
// BUT NEXT CALL TO rename function OVERWRITES IT WITH NEW CONTENT! 

rename($tmp_file_path, $new_file_path); //Attempts to rename oldname to newname, 
// moving it between directories if necessary. If newname exists, it will be 
// overwritten. 

,有什麼解決辦法是存在的PHP使file_exists函數創建一個文件,如果它不存在像touch確實,在一個原子操作?

+0

你可以使用PHP的'exec(「touch」。$ new_file_path);'或者是在這裏關閉限制嗎? –

回答

4

PHP有tempnam功能:

// create a file with unique name in $new_file_path 
$new_file_path = '/path/to/new/location'; 
$tmpfname = tempnam($new_file_path, "foo"); 

根據manual

tempnam創建一個文件名唯一的文件時,設置爲 0600,在指定的目錄訪問權限。如果該目錄不存在, tempnam()可能會在系統的臨時目錄中生成一個文件,並且 會返回該文件的名稱。

+1

http://www.php.net/manual/en/function.tempnam.php#98232說關於非原子。 4.0.3中tempnam的更新日誌表示它們固定了競爭條件。固定的競爭條件=真正的原子,不是嗎? –

+0

是的,固定的競賽條件=真正的原子。看看這個問題的答案討論:http://stackoverflow.com/questions/13018787/safe-unique-filename-with-no-race-condition – user4035