小编典典
更新(12/2015):对于PHP7.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(我尚未测试过。)
2020-05-29