更新(12/2015):对于PHP 7.0,您应该使用
random_int()而不是mt_rand,因为它提供了“加密安全的值”
个人来说,我喜欢使用sha1(microtime(true).mt_rand(10000,90000)),但是你正在寻找更多的可定制的方法,所以尝试这个函数(这是对你的请求this answer的修改):
function rand_char($length) {
$random = '';
for ($i = 0; $i < $length; $i++) {
$random .= chr(mt_rand(33, 126));
}
return $random;
}
仍然,这可能会明显慢于uniqid(),md5()或sha1()。
编辑:看起来你先得到它,对不起。 :D
编辑2:我决定做一个很好的小测试我的Debian机器与PHP 5和eAccelerator(借用长码):
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(我没有测试..)