0

编码:

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

4

1 回答 1

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");

根据手册

tempnam在指定目录中创建具有唯一文件名的文件,访问权限设置为 0600。如果该目录不存在, tempnam()可能会在系统的临时目录中生成一个文件,并返回该文件的名称。

于 2013-05-31T03:50:02.263 回答