file_exists在高负载系统上

时间:2013-05-31 03:42:13

标签: php

代码:

$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那样,在一个原子操作中?

1 个答案:

答案 0 :(得分: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()可能会在系统的临时目录中生成一个文件,并且   返回该名称。