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?


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.

Answered By – gagarine

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published