2013-05-31 53 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