如何按时间高效地生成随机唯一的临时文件名以存储在自定义目录中?

How to Efficiently by Time generate random unique temp File Name for storing in Custom Directory?

结构需要

文件名不必是file-1.txt、file-2.txt.

唯一要求 - 文件必须是唯一的并且具有 .txt 扩展名。

理论上这些文件名可以是

我自己找到的解决方案

function generate_file_name() {
    $file_index = 0;
    do {
        $file_index++;
        $file = "custom-dir/file-$file_index";
    } while( file_exists( $file ) );

    return $file;
}

正在通过 REST POST 请求调用函数 generate_file_name()。 有新上传的文件。

但问题是 - 每个请求都需要从 stratch checking 开始。

从 1 到最大可用文件名。

并且每个请求都会进行 20 000 多次迭代。每次。 目前有 20 000 多个文件。

如何以最少的迭代次数高效地完成这个任务。 没有每次都从 1 到 N 检查所有这些文件?

所以基本上,我要做的是将原始文件名与扩展名分开

<?php 

$fileExt = explode('.', $filename);

$fileActualExt = strtolower(end($fileExt));

然后生成一个唯一的文件名如下,然后附加扩展名

 $fileNameNew = date('Ymdhis',time()).mt_rand().".".$fileActualExt; //current date with hour, minutes and exact seconds + time + random digits
?>

希望你觉得这有用