更新(12/2015):对于 PHP 7.0,您应该使用 random_int()
而不是 mt_rand
因为它提供了“加密安全值”
就个人而言,我喜欢使用,但您正在寻找更多可自定义的方法,因此请尝试此函数(这是对您对此答案请求的修改):sha1(microtime(true).mt_rand(10000,90000))
function rand_char($length) {
$random = '';
for ($i = 0; $i < $length; $i++) {
$random .= chr(mt_rand(33, 126));
}
return $random;
}
尽管如此,这可能比uniqid(),md5()或sha1()慢得多。
编辑:看起来你先到了,对不起。:D
编辑 2:我决定用 PHP 5 和 eAccelerator 在我的 Debian 机器上做一个漂亮的小测试(请原谅长代码):
function rand_char($length) {
$random = '';
for ($i = 0; $i < $length; $i++) {
$random .= chr(mt_rand(33, 126));
}
return $random;
}
function rand_sha1($length) {
$max = ceil($length / 40);
$random = '';
for ($i = 0; $i < $max; $i ++) {
$random .= sha1(microtime(true).mt_rand(10000,90000));
}
return substr($random, 0, $length);
}
function rand_md5($length) {
$max = ceil($length / 32);
$random = '';
for ($i = 0; $i < $max; $i ++) {
$random .= md5(microtime(true).mt_rand(10000,90000));
}
return substr($random, 0, $length);
}
$a = microtime(true);
for ($x = 0; $x < 1000; $x++)
$temp = rand_char(1000);
echo "Rand:\t".(microtime(true) - $a)."\n";
$a = microtime(true);
for ($x = 0; $x < 1000; $x++)
$temp = rand_sha1(1000);
echo "SHA-1:\t".(microtime(true) - $a)."\n";
$a = microtime(true);
for ($x = 0; $x < 1000; $x++)
$temp = rand_md5(1000);
echo "MD5:\t".(microtime(true) - $a)."\n";
结果:
Rand: 2.09621596336
SHA-1: 0.611464977264
MD5: 0.618473052979
因此,如果你想要速度(但不是完整的字符集),我的建议是坚持使用MD5,SHA-1或Uniqid(我还没有测试过)。