Home > php教程 > php手册 > body text

php教程:生成唯一的标识码

WBOY
Release: 2016-06-06 20:09:38
Original
1747 people have browsed it

我们平时可能会在网站上面加一个别致的投稿页面,而在投稿页面,我们可能就会再增加一个更别致贴心的投稿完成自动注册功能。为了安全,这就需要我们生成一个随机的字符串作为临时密码。当然,这种在一定时间内生成唯一的标识码,还经常会用在账户激活。我们

我们平时可能会在网站上面加一个别致的投稿页面,而在投稿页面,我们可能就会再增加一个更别致贴心的投稿完成自动注册功能。为了安全,这就需要我们生成一个随机的字符串作为临时密码。当然,这种在一定时间内生成唯一的标识码,还经常会用在账户激活。我们现在来看看这种标志码的生成方法:可能呢,在同一时间点(精确到微秒)会有N个人来注册帐号,那怎么避免标志码重复呢。

function?random_key($len,$readable=false,$hash=false){ ??
????$key='';? ??
????if?($hash){ ??
????????$key?=?substr(sha1(uniqid(rand(),true)),?0,?$len); ??
????}else?if?($readable){ ??
????????$chars=?'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';? ??
????????for?($i?=?0;?$i?$len;?++$i){ ??
????????????$key?.=?substr($chars,?(mt_rand()?%?strlen($chars)),?1); ??
??????????????????} ??
????}else{ ??
????????for?($i?=?0;?$i?$len;?++$i) ??
????????????$key?.=?chr(mt_rand(33,?126)); ??
?????????} ??
? ??
????return?$key; ??
}??
Copy after login

注意哦,sha1函数第二个参数因为是true,所以会返回20 字符长度的原始格式,如果是false,那么将会返回一个 40 字符长度的十六进制数字字符串。uniqid用于生成唯一ID,第二个参数为true,可以让ID更具唯一性。chr函数用于生成对应的Acsii码。substr函数用于截取

声明: 本文采用 BY-NC-SA 协议进行授权 | IT路人
转载请注明转自《php教程:生成唯一的标识码》

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!