Reputation: 598
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?
Any help is greatly appreciated.
Upvotes: 25
Views: 60911
Reputation: 61
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'];
}
}
Upvotes: 0
Reputation: 198249
Other answers have already covered the topic about creating a (pseudo) unique ID, so I only cover how to set your own session id:
The session id in PHP gets automatically generated, but you can set your own. See session_id()
how to do it.
Exemplary it works like this:
$mySessionId = generate_my_session_id();
$oldId = session_id($mySessionId);
session_start(); // session must start _after_ setting the id.
Upvotes: 1
Reputation: 1567
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;
Upvotes: 0
Reputation: 8258
This is what I use for uniq key in php:
$activation = md5(uniqid(rand(), true));
Upvotes: 7
Reputation: 52372
You can use uniqid to generate unique IDs. Look at the comments for PHP implementations of UUID (universally unique identifier) generation as well.
Upvotes: 12