user826855
user826855

Reputation: 598

Generate a Unique Key

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

Answers (7)

Uti Mac
Uti Mac

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

crysxd
crysxd

Reputation: 3479

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

Upvotes: 3

SeanCannon
SeanCannon

Reputation: 78016

Don't over-complicate it:

$key = md5(microtime().rand());

Upvotes: 58

hakre
hakre

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

rackemup420
rackemup420

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

Amirshk
Amirshk

Reputation: 8258

This is what I use for uniq key in php:

$activation = md5(uniqid(rand(), true));

Upvotes: 7

Dan Grossman
Dan Grossman

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

Related Questions