phprandom

Generate random 5 characters string


I want to create exact 5 random characters string with least possibility of getting duplicated. What would be the best way to do it? Thanks.


Solution

  • $rand = substr(md5(microtime()),rand(0,26),5);
    

    Would be my best guess--Unless you're looking for special characters, too:

    $seed = str_split('abcdefghijklmnopqrstuvwxyz'
                     .'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
                     .'0123456789!@#$%^&*()'); // and any other characters
    shuffle($seed); // probably optional since array_is randomized; this may be redundant
    $rand = '';
    foreach (array_rand($seed, 5) as $k) $rand .= $seed[$k];
    

    Example

    And, for one based on the clock (fewer collisions since it's incremental):

    function incrementalHash($len = 5){
      $charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
      $base = strlen($charset);
      $result = '';
    
      $now = explode(' ', microtime())[1];
      while ($now >= $base){
        $i = (int)$now % $base;
        $result = $charset[$i] . $result;
        $now /= $base;
      }
      return substr(str_repeat($charset[0], $len) . $result, -$len); 
    }
    

    Note: incremental means easier to guess; If you're using this as a salt or a verification token, don't. A salt (now) of "WCWyb" means 5 seconds from now it's "WCWyg")