Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random 5 characters string

Tags:

php

random

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.

like image 255
Peter Avatar asked Mar 25 '11 22:03

Peter


People also ask

How do you generate random strings?

Using the random index number, we have generated the random character from the string alphabet. We then used the StringBuilder class to append all the characters together. If we want to change the random string into lower case, we can use the toLowerCase() method of the String .

What is random string generator?

Random strings can be unique. Used in computing, a random string generator can also be called a random character string generator. This is an important tool if you want to generate a unique set of strings. The utility generates a sequence that lacks a pattern and is random.

How do you generate a random string of characters in Java?

Using randomUUID() java. util. UUID is another Java class that can be used to generate a random string. It offers a static randomUUID() method that returns a random alphanumeric string of 32 characters.


1 Answers

$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 = $now % $base;     $result = $charset[$i] . $result;     $now /= $base;   }   return substr($result, -5); } 

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")

like image 192
Brad Christie Avatar answered Sep 20 '22 15:09

Brad Christie