php 生成唯一密钥
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6564251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generate a Unique Key
提问by user826855
What's the best way of generating a unique key, that can't be guessed easily?
生成无法轻易猜到的唯一密钥的最佳方法是什么?
I would like to create a unique key for both account activation and referral purposes, that includes a checksum to help prevent users from easily guessing other users activation or referral keys.
我想为帐户激活和推荐目的创建一个唯一的密钥,其中包括一个校验和,以帮助防止用户轻松猜测其他用户的激活或推荐密钥。
Also, in PHP is it possible to create you own session key? If so, how would you make this unique?
另外,在 PHP 中是否可以创建自己的会话密钥?如果是这样,您将如何使其独一无二?
Any help is greatly appreciated.
任何帮助是极大的赞赏。
回答by AlienWebguy
Don't over-complicate it:
不要过度复杂化:
$key = md5(microtime().rand());
回答by Dan Grossman
回答by Amirshk
This is what I use for uniq key in php:
这是我在 php 中用于 uniq 键的内容:
$activation = md5(uniqid(rand(), true));
回答by crysxd
Just use PHP's build-in function uniqid()
. See PHP manual.
只需使用 PHP 的内置函数即可uniqid()
。请参阅 PHP 手册。
回答by hakre
Other answers have already covered the topic about creating a (pseudo) unique ID, so I only cover how to set your own session id:
其他答案已经涵盖了有关创建(伪)唯一 ID 的主题,因此我只介绍如何设置自己的会话 ID:
The session id in PHP gets automatically generated, but you can set your own. See session_id()
how to do it.
PHP 中的会话 ID 会自动生成,但您可以设置自己的。看看session_id()
怎么做。
Exemplary it works like this:
示例它的工作方式如下:
$mySessionId = generate_my_session_id();
$oldId = session_id($mySessionId);
session_start(); // session must start _after_ setting the id.
回答by Uti Mac
You can use this function i wrote sometimes ago..
你可以使用我以前写的这个函数..
function generateToken($type = null) {
if($type) {
return '<input type="hidden" name="token_id" value="'.$_SESSION['token_id'].'">';
} else {
if(!isset($_SESSION['token_id'])) {
$token_id = md5(substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 10));
$_SESSION['token_id'] = $token_id;
return $_SESSION['token_id'];
}
return $_SESSION['token_id'];
}
}
回答by rackemup420
I use this script to randomly generate passwords, you change a couple things around and it will work quite well for what you want.
我使用这个脚本来随机生成密码,你改变一些东西,它会很好地满足你的需求。
function generatePassword ($length) {
$possible = "0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRESTUVWXYZ_"; // allowed chars in the password
if ($length == "" OR !is_numeric($lengh)){
$length = 8;
}
srand(make_seed());
$i = 0;
$password = "";
while ($i < $length) {
$char = substr($possible, rand(0, strlen($possible)-1), 1);
if (!strstr($password, $char)) {
$password .= $char;
$i++;
}
}
return $password;
}
and for your own session key its pretty simple
对于您自己的会话密钥,它非常简单
start_session();
$_SESSION['NewSessionVariable']=$VariableToSet;