0

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?

lucas
  • 55
  • 2
  • 10
  • use PHP function `uniqid();`, pro tip: also add a random number of around 8 digits to the end http://php.net/manual/en/function.uniqid.php then to apply to your exact requirements, encode as you wish – pokeybit Apr 25 '18 at 10:33

3 Answers3

2

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.

gagarine
  • 76
  • 5
0

readable - base64_encode(random_bytes($lenght ) ); shorter

readable longer - bin2hex(random_bytes($lenght ) );

To make with wanted length use substr

-1

Use rand function instead of 'random_int'

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

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

 echo random_str('50');

// Output //

P7V55MYPQJGRNQ8W0VW7TRKBDK2B7NXWUT20F0P6J5Y7W63X20
harish patel
  • 136
  • 11