24

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.

user826855
  • 578
  • 1
  • 7
  • 18
  • Duplicate for the Unique Key part of the question: **[Unique key generation](http://stackoverflow.com/questions/55218/unique-key-generation)** – hakre Jul 03 '11 at 17:54

7 Answers7

58

Don't over-complicate it:

$key = md5(microtime().rand());
AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
  • 2
    Which will make sessions/registrations starting at the same time will get the same key. Can over-complicate stuff in hard-to-debug situations. – hakre Jul 03 '11 at 17:18
  • 17
    Welcome to the world of multi-threaded webserver environments and multi core processors. – hakre Jul 03 '11 at 17:26
  • So is this method OK to use, or is there a slim possibility that two or more users will have the same key? – user826855 Jul 03 '11 at 18:56
  • Even two different input values can cause a hash collision. The odds are around 1/750,000 - would not recommend this. – SISYN Sep 23 '15 at 03:00
  • @DanL I don't know where have you extract that probability but for I think is wrong, getting that there is 2^128 posibilities to have 1/750000 you need to have around 10^38 unique hashes before. – PhoneixS Feb 15 '16 at 11:01
  • 1
    Why not add session id to it, to prevent any possible clash? – Scott Flack Mar 07 '16 at 06:07
  • it will clash one day – ujwal dhakal Jun 05 '20 at 05:00
12

You can use uniqid to generate unique IDs. Look at the comments for PHP implementations of UUID (universally unique identifier) generation as well.

Dan Grossman
  • 51,866
  • 10
  • 112
  • 101
  • 1
    Note that most of the suggestions provided in the comments are not guaranteed to be unique as neither pseuso-random number generators nor hash functions return unique values. – Gumbo Jul 03 '11 at 17:13
7

This is what I use for uniq key in php:

$activation = md5(uniqid(rand(), true));
Amirshk
  • 8,170
  • 2
  • 35
  • 64
3

Just use PHP's build-in function uniqid(). See PHP manual.

crysxd
  • 3,177
  • 20
  • 32
1

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.
hakre
  • 193,403
  • 52
  • 435
  • 836
0

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'];
  }
}
Uti Mac
  • 61
  • 1
  • 5
0

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;
rackemup420
  • 1,600
  • 2
  • 15
  • 37
  • idk theres a ton of ways to do it and people can argue over whats better lol :D. – rackemup420 Jul 03 '11 at 17:23
  • I wouldn't use this algorithm in applications hat need security as the random number generation function isn't normally very good in producing good randomized values. Use a hash function like md5 or better sha2 for such things. – Jonny Dee Jul 03 '11 at 18:04