问题描述
uniqid() 根据当前时间戳(以微秒为单位)生成唯一 ID.这真的是生成唯一 ID 的万无一失的方法吗?
uniqid() in PHP generates a unique ID based on the current timestamp in microseconds. Is that really a foolproof way to generate a unique ID?
即使假设有一个用户运行单个脚本,并且循环生成一个以微秒为单位的时间戳,是否真的可以从理论上保证它是不完整的?而在实践中,这种可能性是否完全可以忽略不计?
Even assuming there's a single user running a single script with a loop generating a timestamp in microseconds, can there still really be a theoretical guarantee that it's unqiue? And in practice, is the likelihood completely negligible?
为了清楚起见,说你的循环只不过是这样:
For clarity, say your loop is nothing more than this:
foreach($things as $thing){
var_dump(microtime());
}
是否有任何理论上的机会它可能不是独一无二的,如果是,它在实践中的现实程度如何?
is there any theoretical chance it might not be unique and, if so, how realistic is it in practice?
推荐答案
基于微秒的 id 只保证在限制范围内是唯一的.在这方面,单台计算机上的单线程脚本可能非常安全.但是,一旦您开始谈论并行执行,无论是简单地在同一台机器内的多个 CPU 上,还是特别是在多台机器上,所有的赌注都没有了.
Microsecond based ids are only guaranteed to be unique within limits. A single threaded scripts on a single computer is probably pretty safe in this regard. However, as soon as you start talking about parallel execution, be that simply on multiple CPUs within the same machine or especially across multiple machines, all bets are off.
所以这取决于你想用这个 id 做什么.如果您只是使用它来生成仅在同一脚本中使用的 id,那么它可能足够安全.例如:
So it depends on what you want to use this id for. If you're just using it to generate an id which is used only within the same script, it's probably safe enough. For example:
<?php $randomId = uniqid(); ?>
<div id="<?php echo $randomId; ?>"></div>
<script>
var div = document.getElementById('<?php echo $randomId; ?>');
...
</script>
在这种有限的使用中,您很可能不会遇到任何问题.
You very likely won't encounter any problems here with this limited use.
但是,如果您开始使用 uniqid
或与其他外部脚本共享的其他此类用途生成文件名,我不会依赖它.对于文件名,使用基于文件内容的哈希可能是个好主意.对于通用分散随机生成的 id,UUID 非常适合(因为它们是为这个目的).
However, if you start generating file names using uniqid
or other such uses which are shared with other external scripts, I wouldn't rely on it. For filenames, using a hash based on the file contents may be a good idea. For general purpose decentralised randomly generated ids, UUIDs are a good fit (because they've been designed for this purpose).
这篇关于以微秒为单位的时间戳总是唯一的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!