Skip to content
Advertisement

Generate save activation key as product key

I am trying to create a function which creates a random String. This String should consist of letters (only caps) and numbers. It will be used to activate a product. So the user has to type it into a text field. So far I found the following function:

function random_str($length, $keyspace =  '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'){

  $pieces = [];
  $max = mb_strlen($keyspace, '8bit') - 1;
  for ($i = 0; $i < $length; ++$i) {
      $pieces []= $keyspace[random_int(0, $max)];
  }
  return implode('', $pieces);
}

I do not have that much experience with random functions. So is there anything to improve or would you suggest a different function?

Advertisement

Answer

To generate a cryptographically secure random string (which I would recommend for an activation key), I would rather use openssl_random_pseudo_bytes

You can find the doc here and some useful informations in that thread (for example, how to get a random string with 0-9A-Z characters rather than just 0-9A-F).

As of PHP7.0 you could also use random_bytes, which is also cryptographically secure.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement