Generate random string from 4 to 8 characters in PHP

Viewed 39269

I need to generate a string using PHP, it need to be unique and need to be from 4 to 8 characters (the value of a variable).

I thought I can use crc32 hash but I can't decide how many characters, but sure it will be unique. In the other hand only create a "password generator" will generate duplicated string and checking the value in the table for each string will take a while.

How can I do that?

Thanks!


Maybe I can use that :

  function unique_id(){
  $better_token = md5(uniqid(rand(), true));
  $unique_code = substr($better_token, 16);
  $uniqueid = $unique_code;
  return $uniqueid;
  }

  $id = unique_id();

Changing to :

  function unique_id($l = 8){
  $better_token = md5(uniqid(rand(), true));
      $rem = strlen($better_token)-$l;
  $unique_code = substr($better_token, 0, -$rem);
  $uniqueid = $unique_code;
  return $uniqueid;
  }

  echo unique_id(4);

Do you think I'll get unique string each time for a goood while?

3 Answers

Reliable passwords You can only make from ascii characters a-zA-Z and numbers 0-9. To do that best way is using only cryptographically secure methods, like random_int() or random_bytes() from PHP7. Rest functions as base64_encode() You can use only as support functions to make reliability of string and change it to ASCII characters.

mt_rand() is not secure and is very old. From any string You must use random_int(). From binary string You should use base64_encode() to make binary string reliable or bin2hex, but then You will cut byte only to 16 positions (values). See my implementation of this functions.

Related