Related
How would it be possible to generate a random, unique string using numbers and letters for use in a verify link? Like when you create an account on a website, and it sends you an email with a link, and you have to click that link in order to verify your account
How can I generate one of those using PHP?
PHP 7 standard library provides the random_bytes($length) function that generate cryptographically secure pseudo-random bytes.
Example:
$bytes = random_bytes(20);
var_dump(bin2hex($bytes));
The above example will output something similar to:
string(40) "5fe69c95ed70a9869d9f9af7d8400a6673bb9ce9"
More info: http://php.net/manual/en/function.random-bytes.php
PHP 5 (outdated)
I was just looking into how to solve this same problem, but I also want my function to create a token that can be used for password retrieval as well. This means that I need to limit the ability of the token to be guessed. Because uniqid is based on the time, and according to php.net "the return value is little different from microtime()", uniqid does not meet the criteria. PHP recommends using openssl_random_pseudo_bytes() instead to generate cryptographically secure tokens.
A quick, short and to the point answer is:
bin2hex(openssl_random_pseudo_bytes($bytes))
which will generate a random string of alphanumeric characters of length = $bytes * 2. Unfortunately this only has an alphabet of [a-f][0-9], but it works.
Below is the strongest function I could make that satisfies the criteria (This is an implemented version of Erik's answer).
function crypto_rand_secure($min, $max)
{
$range = $max - $min;
if ($range < 1) return $min; // not so random...
$log = ceil(log($range, 2));
$bytes = (int) ($log / 8) + 1; // length in bytes
$bits = (int) $log + 1; // length in bits
$filter = (int) (1 << $bits) - 1; // set all lower bits to 1
do {
$rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
$rnd = $rnd & $filter; // discard irrelevant bits
} while ($rnd > $range);
return $min + $rnd;
}
function getToken($length)
{
$token = "";
$codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
$codeAlphabet.= "0123456789";
$max = strlen($codeAlphabet); // edited
for ($i=0; $i < $length; $i++) {
$token .= $codeAlphabet[crypto_rand_secure(0, $max-1)];
}
return $token;
}
crypto_rand_secure($min, $max) works as a drop in replacement for rand() or mt_rand. It uses openssl_random_pseudo_bytes to help create a random number between $min and $max.
getToken($length) creates an alphabet to use within the token and then creates a string of length $length.
Source: http://us1.php.net/manual/en/function.openssl-random-pseudo-bytes.php#104322
Security Notice: This solution should not be used in situations where the quality of your randomness can affect the security of an application. In particular, rand() and uniqid() are not cryptographically secure random number generators. See Scott's answer for a secure alternative.
If you do not need it to be absolutely unique over time:
md5(uniqid(rand(), true))
Otherwise (given you have already determined a unique login for your user):
md5(uniqid($your_user_login, true))
Object-oriented version of the most up-voted solution
I've created an object-oriented solution based on Scott's answer:
<?php
namespace Utils;
/**
* Class RandomStringGenerator
* #package Utils
*
* Solution taken from here:
* http://stackoverflow.com/a/13733588/1056679
*/
class RandomStringGenerator
{
/** #var string */
protected $alphabet;
/** #var int */
protected $alphabetLength;
/**
* #param string $alphabet
*/
public function __construct($alphabet = '')
{
if ('' !== $alphabet) {
$this->setAlphabet($alphabet);
} else {
$this->setAlphabet(
implode(range('a', 'z'))
. implode(range('A', 'Z'))
. implode(range(0, 9))
);
}
}
/**
* #param string $alphabet
*/
public function setAlphabet($alphabet)
{
$this->alphabet = $alphabet;
$this->alphabetLength = strlen($alphabet);
}
/**
* #param int $length
* #return string
*/
public function generate($length)
{
$token = '';
for ($i = 0; $i < $length; $i++) {
$randomKey = $this->getRandomInteger(0, $this->alphabetLength);
$token .= $this->alphabet[$randomKey];
}
return $token;
}
/**
* #param int $min
* #param int $max
* #return int
*/
protected function getRandomInteger($min, $max)
{
$range = ($max - $min);
if ($range < 0) {
// Not so random...
return $min;
}
$log = log($range, 2);
// Length in bytes.
$bytes = (int) ($log / 8) + 1;
// Length in bits.
$bits = (int) $log + 1;
// Set all lower bits to 1.
$filter = (int) (1 << $bits) - 1;
do {
$rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
// Discard irrelevant bits.
$rnd = $rnd & $filter;
} while ($rnd >= $range);
return ($min + $rnd);
}
}
Usage
<?php
use Utils\RandomStringGenerator;
// Create new instance of generator class.
$generator = new RandomStringGenerator;
// Set token length.
$tokenLength = 32;
// Call method to generate random string.
$token = $generator->generate($tokenLength);
Custom alphabet
You can use custom alphabet if required.
Just pass a string with supported chars to the constructor or setter:
<?php
$customAlphabet = '0123456789ABCDEF';
// Set initial alphabet.
$generator = new RandomStringGenerator($customAlphabet);
// Change alphabet whenever needed.
$generator->setAlphabet($customAlphabet);
Here's the output samples
SRniGU2sRQb2K1ylXKnWwZr4HrtdRgrM
q1sRUjNq1K9rG905aneFzyD5IcqD4dlC
I0euIWffrURLKCCJZ5PQFcNUCto6cQfD
AKwPJMEM5ytgJyJyGqoD5FQwxv82YvMr
duoRF6gAawNOEQRICnOUNYmStWmOpEgS
sdHUkEn4565AJoTtkc8EqJ6cC4MLEHUx
eVywMdYXczuZmHaJ50nIVQjOidEVkVna
baJGt7cdLDbIxMctLsEBWgAw5BByP5V0
iqT0B2obq3oerbeXkDVLjZrrLheW4d8f
OUQYCny6tj2TYDlTuu1KsnUyaLkeObwa
I hope it will help someone. Cheers!
I'm here with some good research data based on the functions provided by Scott's answer. So I set up a Digital Ocean droplet just for this 5-day long automated test and stored the generated unique strings in a MySQL database.
During this test period, I used 5 different lengths (5, 10, 15, 20, 50) and +/-0.5 million records were inserted for each length. During my test, only the length 5 generated +/-3K duplicates out of 0.5 million and the remaining lengths didn't generate any duplicates. So we can say that if we use a length of 15 or above with Scott's functions, then we can generate highly reliable unique strings. Here is the table showing my research data:
Update
I created a simple Heroku app using these functions that returns the token as a JSON response. The app can be accessed at https://uniquestrings.herokuapp.com/api/token?length=15
You can use UUID(Universally Unique Identifier), it can be used for any purpose, from user authentication string to payment transaction id.
A UUID is a 16-octet (128-bit) number. In its canonical form, a UUID is represented by 32 hexadecimal digits, displayed in five groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 alphanumeric characters and four hyphens).
function generate_uuid() {
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
mt_rand( 0, 0xffff ),
mt_rand( 0, 0x0C2f ) | 0x4000,
mt_rand( 0, 0x3fff ) | 0x8000,
mt_rand( 0, 0x2Aff ), mt_rand( 0, 0xffD3 ), mt_rand( 0, 0xff4B )
);
}
//calling funtion
$transationID = generate_uuid();
some example outputs will be like:
E302D66D-87E3-4450-8CB6-17531895BF14
22D288BC-7289-442B-BEEA-286777D559F2
51B4DE29-3B71-4FD2-9E6C-071703E1FF31
3777C8C6-9FF5-4C78-AAA2-08A47F555E81
54B91C72-2CF4-4501-A6E9-02A60DCBAE4C
60F75C7C-1AE3-417B-82C8-14D456542CD7
8DE0168D-01D3-4502-9E59-10D665CEBCB2
hope it helps someone in future :)
This function will generate a random key using numbers and letters:
function random_string($length) {
$key = '';
$keys = array_merge(range(0, 9), range('a', 'z'));
for ($i = 0; $i < $length; $i++) {
$key .= $keys[array_rand($keys)];
}
return $key;
}
echo random_string(50);
Example output:
zsd16xzv3jsytnp87tk7ygv73k8zmr0ekh6ly7mxaeyeh46oe8
I use this one-liner:
base64_encode(openssl_random_pseudo_bytes(3 * ($length >> 2)));
where length is the length of the desired string (divisible by 4, otherwise it gets rounded down to the nearest number divisible by 4)
Use the code below to generate the random number of 11 characters or change the number as per your requirement.
$randomNum=substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyz"), 0, 11);
or we can use custom function to generate the random number
function randomNumber($length){
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $length;$i++)
$digits .= $numbers[$i];
return $digits;
}
//generate random number
$randomNum=randomNumber(11);
Generate a random number using
your favourite random-number
generator
Multiply and divide it
to get a number matching the number
of characters in your code alphabet
Get the item at that index in
your code alphabet.
Repeat from 1) until you have the length you
want
e.g (in pseudo code)
int myInt = random(0, numcharacters)
char[] codealphabet = 'ABCDEF12345'
char random = codealphabet[i]
repeat until long enough
For really random strings, you can use
<?php
echo md5(microtime(true).mt_Rand());
outputs :
40a29479ec808ad4bcff288a48a25d5c
so even if you try to generate string multiple times at exact same time, you will get different output.
This is a simple function that allows you to generate random strings containing Letters and Numbers (alphanumeric). You can also limit the string length.
These random strings can be used for various purposes, including: Referral Code, Promotional Code, Coupon Code.
Function relies on following PHP functions:
base_convert, sha1, uniqid, mt_rand
function random_code($length)
{
return substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, $length);
}
echo random_code(6);
/*sample output
* a7d9e8
* 3klo93
*/
When trying to generate a random password you are trying to :
First generate a cryptographically secure set of random bytes
Second is turning those random bytes into a printable string
Now, there are multiple way to generate random bytes in php like :
$length = 32;
//PHP 7+
$bytes= random_bytes($length);
//PHP < 7
$bytes= openssl_random_pseudo_bytes($length);
Then you want to turn these random bytes into a printable string :
You can use bin2hex :
$string = bin2hex($bytes);
or base64_encode :
$string = base64_encode($bytes);
However, note that you do not control the length of the string if you use base64.
You can use bin2hex to do that, using 32 bytes will turn into a 64 char string.
But it will only work like so in an EVEN string.
So basically you can just do :
$length = 32;
if(PHP_VERSION>=7){
$bytes= random_bytes($length);
}else{
$bytes= openssl_random_pseudo_bytes($length);
}
$string = bin2hex($bytes);
Here is what I use:
md5(time() . rand());
// Creates something like 0c947c3b1047334f5bb8a3b7adc1d97b
This people choking on a glass of water...
$random= substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ*.-_"), 0, 10);
Simple.
The posibility to this random string repeat is 0,000000000000000000000000000001^70
Here is ultimate unique id generator for you. made by me.
<?php
$d=date ("d");
$m=date ("m");
$y=date ("Y");
$t=time();
$dmt=$d+$m+$y+$t;
$ran= rand(0,10000000);
$dmtran= $dmt+$ran;
$un= uniqid();
$dmtun = $dmt.$un;
$mdun = md5($dmtran.$un);
$sort=substr($mdun, 16); // if you want sort length code.
echo $mdun;
?>
you can echo any 'var' for your id as you like. but $mdun is better, you can replace md5 to sha1 for better code but that will be very long which may you dont need.
Thank you.
I like to use hash keys when dealing verification links. I would recommend using the microtime and hashing that using MD5 since there should be no reason why the keys should be the same since it hashes based off of the microtime.
$key = md5(rand());
$key = md5(microtime());
function random_string($length = 8) {
$alphabets = range('A','Z');
$numbers = range('0','9');
$additional_characters = array('_','=');
$final_array = array_merge($alphabets,$numbers,$additional_characters);
while($length--) {
$key = array_rand($final_array);
$password .= $final_array[$key];
}
if (preg_match('/[A-Za-z0-9]/', $password))
{
return $password;
}else{
return random_string();
}
}
Simple 'one line' string hash generator like
77zd43-7bc495-64cg9a-535548 (1byte = 2chars)
$hash = implode('-', [
bin2hex(random_bytes(3)),
bin2hex(random_bytes(3)),
bin2hex(random_bytes(3)),
bin2hex(random_bytes(3)),
]);
after reading previous examples I came up with this:
protected static $nonce_length = 32;
public static function getNonce()
{
$chars = array();
for ($i = 0; $i < 10; $i++)
$chars = array_merge($chars, range(0, 9), range('A', 'Z'));
shuffle($chars);
$start = mt_rand(0, count($chars) - self::$nonce_length);
return substr(join('', $chars), $start, self::$nonce_length);
}
I duplicate 10 times the array[0-9,A-Z] and shuffle the elements, after I get a random start point for substr() to be more 'creative' :)
you can add [a-z] and other elements to array, duplicate more or less, be more creative than me
<?php
function generateRandomString($length = 11) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
?>
above function will generate you a random string which is length of 11 characters.
If you want to generate a unique string in PHP, try following.
md5(uniqid().mt_rand());
In this,
uniqid() - It will generate unique string. This function returns timestamp based unique identifier as a string.
mt_rand() - Generate random number.
md5() - It will generate the hash string.
A simple solution is to convert base 64 to alphanumeric by discarding the non-alphanumeric characters.
This one uses random_bytes() for a cryptographically secure result.
function random_alphanumeric(int $length): string
{
$result='';
do
{
//Base 64 produces 4 characters for each 3 bytes, so most times this will give enough bytes in a single pass
$bytes=random_bytes(($length+3-strlen($result))*2);
//Discard non-alhpanumeric characters
$result.=str_replace(['/','+','='],['','',''],base64_encode($bytes));
//Keep adding characters until the string is long enough
//Add a few extra because the last 2 or 3 characters of a base 64 string tend to be less diverse
}while(strlen($result)<$length+3);
return substr($result,0,$length);
}
Edit: I just revisited this because I need something a bit more flexible. Here is a solution that performs a bit better than the above and gives the option to specify any subset of the ASCII character set:
<?php
class RandomText
{
protected
$allowedChars,
//Maximum index to use
$allowedCount,
//Index values will be taken from a pool of this size
//It is a power of 2 to keep the distribution of values even
$distributionSize,
//This many characters will be generated for each output character
$ratio;
/**
* #param string $allowedChars characters to choose from
*/
public function __construct(string $allowedChars)
{
$this->allowedCount = strlen($allowedChars);
if($this->allowedCount < 1 || $this->allowedCount > 256) throw new \Exception('At least 1 and no more than 256 allowed character(s) must be specified.');
$this->allowedChars = $allowedChars;
//Find the power of 2 equal or greater than the number of allowed characters
$this->distributionSize = pow(2,ceil(log($this->allowedCount, 2)));
//Generating random bytes is the expensive part of this algorithm
//In most cases some will be wasted so it is helpful to produce some extras, but not too many
//On average, this is how many characters needed to produce 1 character in the allowed set
//50% of the time, more characters will be needed. My tests have shown this to perform well.
$this->ratio = $this->distributionSize / $this->allowedCount;
}
/**
* #param int $length string length of required result
* #return string random text
*/
public function get(int $length) : string
{
if($length < 1) throw new \Exception('$length must be >= 1.');
$result = '';
//Keep track of result length to prevent having to compute strlen()
$l = 0;
$indices = null;
$i = null;
do
{
//Bytes will be used to index the character set. Convert to integers.
$indices = unpack('C*', random_bytes(ceil(($length - $l) * $this->ratio)));
foreach($indices as $i)
{
//Reduce to the smallest range that gives an even distribution
$i %= $this->distributionSize;
//If the index is within the range of characters, add one char to the string
if($i < $this->allowedCount)
{
$l++;
$result .= $this->allowedChars[$i];
}
if($l >= $length) break;
}
}while($l < $length);
return $result;
}
}
one can use this code. i tested with 35,000,00 IDs no duplicates.
<?php
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_';
$result = '';
for ($i = 0; $i < 11; $i++)
$result .= $characters[mt_rand(0, 63)];?>
you are free to modify it as your need. and if you have any suggestions feel free to comment.it is recommended that you should check every id in your database before using this ids by doing that you have 100% unique ids in your database.
function codeGenerate() {
$randCode = (string)mt_rand(1000,9999);
$randChar = rand(65,90);
$randInx = rand(0,3);
$randCode[$randInx] = chr($randChar);
return $randCode;
}
echo codeGenerate();
OUTPUT
38I7
33V7
E836
736U
I always use this my function to generate a custom random alphanumeric string... Hope this help.
<?php
function random_alphanumeric($length) {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12345689';
$my_string = '';
for ($i = 0; $i < $length; $i++) {
$pos = random_int(0, strlen($chars) -1);
$my_string .= substr($chars, $pos, 1);
}
return $my_string;
}
echo random_alphanumeric(50); // 50 characters
?>
It generates for example: Y1FypdjVbFCFK6Gh9FDJpe6dciwJEfV6MQGpJqAfuijaYSZ86g
If you want compare with another string to be sure that is a unique sequence you can use this trick...
$string_1 = random_alphanumeric(50);
$string_2 = random_alphanumeric(50);
while ($string_1 == $string_2) {
$string_1 = random_alphanumeric(50);
$string_2 = random_alphanumeric(50);
if ($string_1 != $string_2) {
break;
}
}
echo $string_1;
echo "<br>\n";
echo $string_2;
it generate two unique strings:
qsBDs4JOoVRfFxyLAOGECYIsWvpcpMzAO9pypwxsqPKeAmYLOi
Ti3kE1WfGgTNxQVXtbNNbhhvvapnaUfGMVJecHkUjHbuCb85pF
Hope this is what you are looking for...
Scott, yes you are very write and good solution! Thanks.
I am also required to generate unique API token for my each user. Following is my approach, i used user information (Userid and Username):
public function generateUniqueToken($userid, $username){
$rand = mt_rand(100,999);
$md5 = md5($userid.'!(&^ 532567_465 ///'.$username);
$md53 = substr($md5,0,3);
$md5_remaining = substr($md5,3);
$md5 = $md53. $rand. $userid. $md5_remaining;
return $md5;
}
Please have a look and let me know if any improvement i can do. Thanks
Here is what I'm using on one of my projects, it's working great and it generates a UNIQUE RANDOM TOKEN:
$timestampz=time();
function generateRandomString($length = 60) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
$tokenparta = generateRandomString();
$token = $timestampz*3 . $tokenparta;
echo $token;
Please note that I multiplied the timestamp by three to create a confusion for whoever user might be wondering how this token is generated ;)
I hope it helps :)
I think this is the best method to use.
str_shuffle(md5(rand(0,100000)))
Here is a fun one
public function randomStr($length = 16) {
$string = '';
while (($len = strlen($string)) < $length) {
$size = $length - $len;
$bytes = random_bytes($size);
$string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
}
return $string;
}
Stolen from laravel here
I believe the problem with all the existing ideas is that they are probably unique, but not definitely unique (as pointed out in Dariusz Walczak's reply to loletech). I have a solution that actually is unique. It requires that your script have some sort of memory. For me this is a SQL database. You could also simply write to a file somewhere. There are two implementations:
First method: have TWO fields rather than 1 that provide uniqueness. The first field is an ID number that is not random but is unique (The first ID is 1, the second 2...). If you are using SQL, just define the ID field with the AUTO_INCREMENT property. The second field is not unique but is random. This can be generated with any of the other techniques people have already mentioned. Scott's idea was good, but md5 is convenient and probably good enough for most purposes:
$random_token = md5($_SERVER['HTTP_USER_AGENT'] . time());
Second method: Basically the same idea, but initially pick a maximum number of strings that will ever be generated. This could just be a really big number like a trillion. Then do the same thing, generate an ID, but zero pad it so that all IDs are the same number of digits. Then just concatenate the ID with the random string. It will be random enough for most purposes, but the ID section will ensure that it is also unique.
How would it be possible to generate a random, unique string using numbers and letters for use in a verify link? Like when you create an account on a website, and it sends you an email with a link, and you have to click that link in order to verify your account
How can I generate one of those using PHP?
PHP 7 standard library provides the random_bytes($length) function that generate cryptographically secure pseudo-random bytes.
Example:
$bytes = random_bytes(20);
var_dump(bin2hex($bytes));
The above example will output something similar to:
string(40) "5fe69c95ed70a9869d9f9af7d8400a6673bb9ce9"
More info: http://php.net/manual/en/function.random-bytes.php
PHP 5 (outdated)
I was just looking into how to solve this same problem, but I also want my function to create a token that can be used for password retrieval as well. This means that I need to limit the ability of the token to be guessed. Because uniqid is based on the time, and according to php.net "the return value is little different from microtime()", uniqid does not meet the criteria. PHP recommends using openssl_random_pseudo_bytes() instead to generate cryptographically secure tokens.
A quick, short and to the point answer is:
bin2hex(openssl_random_pseudo_bytes($bytes))
which will generate a random string of alphanumeric characters of length = $bytes * 2. Unfortunately this only has an alphabet of [a-f][0-9], but it works.
Below is the strongest function I could make that satisfies the criteria (This is an implemented version of Erik's answer).
function crypto_rand_secure($min, $max)
{
$range = $max - $min;
if ($range < 1) return $min; // not so random...
$log = ceil(log($range, 2));
$bytes = (int) ($log / 8) + 1; // length in bytes
$bits = (int) $log + 1; // length in bits
$filter = (int) (1 << $bits) - 1; // set all lower bits to 1
do {
$rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
$rnd = $rnd & $filter; // discard irrelevant bits
} while ($rnd > $range);
return $min + $rnd;
}
function getToken($length)
{
$token = "";
$codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
$codeAlphabet.= "0123456789";
$max = strlen($codeAlphabet); // edited
for ($i=0; $i < $length; $i++) {
$token .= $codeAlphabet[crypto_rand_secure(0, $max-1)];
}
return $token;
}
crypto_rand_secure($min, $max) works as a drop in replacement for rand() or mt_rand. It uses openssl_random_pseudo_bytes to help create a random number between $min and $max.
getToken($length) creates an alphabet to use within the token and then creates a string of length $length.
Source: http://us1.php.net/manual/en/function.openssl-random-pseudo-bytes.php#104322
Security Notice: This solution should not be used in situations where the quality of your randomness can affect the security of an application. In particular, rand() and uniqid() are not cryptographically secure random number generators. See Scott's answer for a secure alternative.
If you do not need it to be absolutely unique over time:
md5(uniqid(rand(), true))
Otherwise (given you have already determined a unique login for your user):
md5(uniqid($your_user_login, true))
Object-oriented version of the most up-voted solution
I've created an object-oriented solution based on Scott's answer:
<?php
namespace Utils;
/**
* Class RandomStringGenerator
* #package Utils
*
* Solution taken from here:
* http://stackoverflow.com/a/13733588/1056679
*/
class RandomStringGenerator
{
/** #var string */
protected $alphabet;
/** #var int */
protected $alphabetLength;
/**
* #param string $alphabet
*/
public function __construct($alphabet = '')
{
if ('' !== $alphabet) {
$this->setAlphabet($alphabet);
} else {
$this->setAlphabet(
implode(range('a', 'z'))
. implode(range('A', 'Z'))
. implode(range(0, 9))
);
}
}
/**
* #param string $alphabet
*/
public function setAlphabet($alphabet)
{
$this->alphabet = $alphabet;
$this->alphabetLength = strlen($alphabet);
}
/**
* #param int $length
* #return string
*/
public function generate($length)
{
$token = '';
for ($i = 0; $i < $length; $i++) {
$randomKey = $this->getRandomInteger(0, $this->alphabetLength);
$token .= $this->alphabet[$randomKey];
}
return $token;
}
/**
* #param int $min
* #param int $max
* #return int
*/
protected function getRandomInteger($min, $max)
{
$range = ($max - $min);
if ($range < 0) {
// Not so random...
return $min;
}
$log = log($range, 2);
// Length in bytes.
$bytes = (int) ($log / 8) + 1;
// Length in bits.
$bits = (int) $log + 1;
// Set all lower bits to 1.
$filter = (int) (1 << $bits) - 1;
do {
$rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
// Discard irrelevant bits.
$rnd = $rnd & $filter;
} while ($rnd >= $range);
return ($min + $rnd);
}
}
Usage
<?php
use Utils\RandomStringGenerator;
// Create new instance of generator class.
$generator = new RandomStringGenerator;
// Set token length.
$tokenLength = 32;
// Call method to generate random string.
$token = $generator->generate($tokenLength);
Custom alphabet
You can use custom alphabet if required.
Just pass a string with supported chars to the constructor or setter:
<?php
$customAlphabet = '0123456789ABCDEF';
// Set initial alphabet.
$generator = new RandomStringGenerator($customAlphabet);
// Change alphabet whenever needed.
$generator->setAlphabet($customAlphabet);
Here's the output samples
SRniGU2sRQb2K1ylXKnWwZr4HrtdRgrM
q1sRUjNq1K9rG905aneFzyD5IcqD4dlC
I0euIWffrURLKCCJZ5PQFcNUCto6cQfD
AKwPJMEM5ytgJyJyGqoD5FQwxv82YvMr
duoRF6gAawNOEQRICnOUNYmStWmOpEgS
sdHUkEn4565AJoTtkc8EqJ6cC4MLEHUx
eVywMdYXczuZmHaJ50nIVQjOidEVkVna
baJGt7cdLDbIxMctLsEBWgAw5BByP5V0
iqT0B2obq3oerbeXkDVLjZrrLheW4d8f
OUQYCny6tj2TYDlTuu1KsnUyaLkeObwa
I hope it will help someone. Cheers!
I'm here with some good research data based on the functions provided by Scott's answer. So I set up a Digital Ocean droplet just for this 5-day long automated test and stored the generated unique strings in a MySQL database.
During this test period, I used 5 different lengths (5, 10, 15, 20, 50) and +/-0.5 million records were inserted for each length. During my test, only the length 5 generated +/-3K duplicates out of 0.5 million and the remaining lengths didn't generate any duplicates. So we can say that if we use a length of 15 or above with Scott's functions, then we can generate highly reliable unique strings. Here is the table showing my research data:
Update
I created a simple Heroku app using these functions that returns the token as a JSON response. The app can be accessed at https://uniquestrings.herokuapp.com/api/token?length=15
You can use UUID(Universally Unique Identifier), it can be used for any purpose, from user authentication string to payment transaction id.
A UUID is a 16-octet (128-bit) number. In its canonical form, a UUID is represented by 32 hexadecimal digits, displayed in five groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 alphanumeric characters and four hyphens).
function generate_uuid() {
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
mt_rand( 0, 0xffff ),
mt_rand( 0, 0x0C2f ) | 0x4000,
mt_rand( 0, 0x3fff ) | 0x8000,
mt_rand( 0, 0x2Aff ), mt_rand( 0, 0xffD3 ), mt_rand( 0, 0xff4B )
);
}
//calling funtion
$transationID = generate_uuid();
some example outputs will be like:
E302D66D-87E3-4450-8CB6-17531895BF14
22D288BC-7289-442B-BEEA-286777D559F2
51B4DE29-3B71-4FD2-9E6C-071703E1FF31
3777C8C6-9FF5-4C78-AAA2-08A47F555E81
54B91C72-2CF4-4501-A6E9-02A60DCBAE4C
60F75C7C-1AE3-417B-82C8-14D456542CD7
8DE0168D-01D3-4502-9E59-10D665CEBCB2
hope it helps someone in future :)
This function will generate a random key using numbers and letters:
function random_string($length) {
$key = '';
$keys = array_merge(range(0, 9), range('a', 'z'));
for ($i = 0; $i < $length; $i++) {
$key .= $keys[array_rand($keys)];
}
return $key;
}
echo random_string(50);
Example output:
zsd16xzv3jsytnp87tk7ygv73k8zmr0ekh6ly7mxaeyeh46oe8
I use this one-liner:
base64_encode(openssl_random_pseudo_bytes(3 * ($length >> 2)));
where length is the length of the desired string (divisible by 4, otherwise it gets rounded down to the nearest number divisible by 4)
Use the code below to generate the random number of 11 characters or change the number as per your requirement.
$randomNum=substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyz"), 0, 11);
or we can use custom function to generate the random number
function randomNumber($length){
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $length;$i++)
$digits .= $numbers[$i];
return $digits;
}
//generate random number
$randomNum=randomNumber(11);
Generate a random number using
your favourite random-number
generator
Multiply and divide it
to get a number matching the number
of characters in your code alphabet
Get the item at that index in
your code alphabet.
Repeat from 1) until you have the length you
want
e.g (in pseudo code)
int myInt = random(0, numcharacters)
char[] codealphabet = 'ABCDEF12345'
char random = codealphabet[i]
repeat until long enough
For really random strings, you can use
<?php
echo md5(microtime(true).mt_Rand());
outputs :
40a29479ec808ad4bcff288a48a25d5c
so even if you try to generate string multiple times at exact same time, you will get different output.
This is a simple function that allows you to generate random strings containing Letters and Numbers (alphanumeric). You can also limit the string length.
These random strings can be used for various purposes, including: Referral Code, Promotional Code, Coupon Code.
Function relies on following PHP functions:
base_convert, sha1, uniqid, mt_rand
function random_code($length)
{
return substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, $length);
}
echo random_code(6);
/*sample output
* a7d9e8
* 3klo93
*/
When trying to generate a random password you are trying to :
First generate a cryptographically secure set of random bytes
Second is turning those random bytes into a printable string
Now, there are multiple way to generate random bytes in php like :
$length = 32;
//PHP 7+
$bytes= random_bytes($length);
//PHP < 7
$bytes= openssl_random_pseudo_bytes($length);
Then you want to turn these random bytes into a printable string :
You can use bin2hex :
$string = bin2hex($bytes);
or base64_encode :
$string = base64_encode($bytes);
However, note that you do not control the length of the string if you use base64.
You can use bin2hex to do that, using 32 bytes will turn into a 64 char string.
But it will only work like so in an EVEN string.
So basically you can just do :
$length = 32;
if(PHP_VERSION>=7){
$bytes= random_bytes($length);
}else{
$bytes= openssl_random_pseudo_bytes($length);
}
$string = bin2hex($bytes);
Here is what I use:
md5(time() . rand());
// Creates something like 0c947c3b1047334f5bb8a3b7adc1d97b
This people choking on a glass of water...
$random= substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ*.-_"), 0, 10);
Simple.
The posibility to this random string repeat is 0,000000000000000000000000000001^70
Here is ultimate unique id generator for you. made by me.
<?php
$d=date ("d");
$m=date ("m");
$y=date ("Y");
$t=time();
$dmt=$d+$m+$y+$t;
$ran= rand(0,10000000);
$dmtran= $dmt+$ran;
$un= uniqid();
$dmtun = $dmt.$un;
$mdun = md5($dmtran.$un);
$sort=substr($mdun, 16); // if you want sort length code.
echo $mdun;
?>
you can echo any 'var' for your id as you like. but $mdun is better, you can replace md5 to sha1 for better code but that will be very long which may you dont need.
Thank you.
I like to use hash keys when dealing verification links. I would recommend using the microtime and hashing that using MD5 since there should be no reason why the keys should be the same since it hashes based off of the microtime.
$key = md5(rand());
$key = md5(microtime());
function random_string($length = 8) {
$alphabets = range('A','Z');
$numbers = range('0','9');
$additional_characters = array('_','=');
$final_array = array_merge($alphabets,$numbers,$additional_characters);
while($length--) {
$key = array_rand($final_array);
$password .= $final_array[$key];
}
if (preg_match('/[A-Za-z0-9]/', $password))
{
return $password;
}else{
return random_string();
}
}
Simple 'one line' string hash generator like
77zd43-7bc495-64cg9a-535548 (1byte = 2chars)
$hash = implode('-', [
bin2hex(random_bytes(3)),
bin2hex(random_bytes(3)),
bin2hex(random_bytes(3)),
bin2hex(random_bytes(3)),
]);
after reading previous examples I came up with this:
protected static $nonce_length = 32;
public static function getNonce()
{
$chars = array();
for ($i = 0; $i < 10; $i++)
$chars = array_merge($chars, range(0, 9), range('A', 'Z'));
shuffle($chars);
$start = mt_rand(0, count($chars) - self::$nonce_length);
return substr(join('', $chars), $start, self::$nonce_length);
}
I duplicate 10 times the array[0-9,A-Z] and shuffle the elements, after I get a random start point for substr() to be more 'creative' :)
you can add [a-z] and other elements to array, duplicate more or less, be more creative than me
<?php
function generateRandomString($length = 11) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
?>
above function will generate you a random string which is length of 11 characters.
If you want to generate a unique string in PHP, try following.
md5(uniqid().mt_rand());
In this,
uniqid() - It will generate unique string. This function returns timestamp based unique identifier as a string.
mt_rand() - Generate random number.
md5() - It will generate the hash string.
A simple solution is to convert base 64 to alphanumeric by discarding the non-alphanumeric characters.
This one uses random_bytes() for a cryptographically secure result.
function random_alphanumeric(int $length): string
{
$result='';
do
{
//Base 64 produces 4 characters for each 3 bytes, so most times this will give enough bytes in a single pass
$bytes=random_bytes(($length+3-strlen($result))*2);
//Discard non-alhpanumeric characters
$result.=str_replace(['/','+','='],['','',''],base64_encode($bytes));
//Keep adding characters until the string is long enough
//Add a few extra because the last 2 or 3 characters of a base 64 string tend to be less diverse
}while(strlen($result)<$length+3);
return substr($result,0,$length);
}
Edit: I just revisited this because I need something a bit more flexible. Here is a solution that performs a bit better than the above and gives the option to specify any subset of the ASCII character set:
<?php
class RandomText
{
protected
$allowedChars,
//Maximum index to use
$allowedCount,
//Index values will be taken from a pool of this size
//It is a power of 2 to keep the distribution of values even
$distributionSize,
//This many characters will be generated for each output character
$ratio;
/**
* #param string $allowedChars characters to choose from
*/
public function __construct(string $allowedChars)
{
$this->allowedCount = strlen($allowedChars);
if($this->allowedCount < 1 || $this->allowedCount > 256) throw new \Exception('At least 1 and no more than 256 allowed character(s) must be specified.');
$this->allowedChars = $allowedChars;
//Find the power of 2 equal or greater than the number of allowed characters
$this->distributionSize = pow(2,ceil(log($this->allowedCount, 2)));
//Generating random bytes is the expensive part of this algorithm
//In most cases some will be wasted so it is helpful to produce some extras, but not too many
//On average, this is how many characters needed to produce 1 character in the allowed set
//50% of the time, more characters will be needed. My tests have shown this to perform well.
$this->ratio = $this->distributionSize / $this->allowedCount;
}
/**
* #param int $length string length of required result
* #return string random text
*/
public function get(int $length) : string
{
if($length < 1) throw new \Exception('$length must be >= 1.');
$result = '';
//Keep track of result length to prevent having to compute strlen()
$l = 0;
$indices = null;
$i = null;
do
{
//Bytes will be used to index the character set. Convert to integers.
$indices = unpack('C*', random_bytes(ceil(($length - $l) * $this->ratio)));
foreach($indices as $i)
{
//Reduce to the smallest range that gives an even distribution
$i %= $this->distributionSize;
//If the index is within the range of characters, add one char to the string
if($i < $this->allowedCount)
{
$l++;
$result .= $this->allowedChars[$i];
}
if($l >= $length) break;
}
}while($l < $length);
return $result;
}
}
one can use this code. i tested with 35,000,00 IDs no duplicates.
<?php
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_';
$result = '';
for ($i = 0; $i < 11; $i++)
$result .= $characters[mt_rand(0, 63)];?>
you are free to modify it as your need. and if you have any suggestions feel free to comment.it is recommended that you should check every id in your database before using this ids by doing that you have 100% unique ids in your database.
function codeGenerate() {
$randCode = (string)mt_rand(1000,9999);
$randChar = rand(65,90);
$randInx = rand(0,3);
$randCode[$randInx] = chr($randChar);
return $randCode;
}
echo codeGenerate();
OUTPUT
38I7
33V7
E836
736U
I always use this my function to generate a custom random alphanumeric string... Hope this help.
<?php
function random_alphanumeric($length) {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12345689';
$my_string = '';
for ($i = 0; $i < $length; $i++) {
$pos = random_int(0, strlen($chars) -1);
$my_string .= substr($chars, $pos, 1);
}
return $my_string;
}
echo random_alphanumeric(50); // 50 characters
?>
It generates for example: Y1FypdjVbFCFK6Gh9FDJpe6dciwJEfV6MQGpJqAfuijaYSZ86g
If you want compare with another string to be sure that is a unique sequence you can use this trick...
$string_1 = random_alphanumeric(50);
$string_2 = random_alphanumeric(50);
while ($string_1 == $string_2) {
$string_1 = random_alphanumeric(50);
$string_2 = random_alphanumeric(50);
if ($string_1 != $string_2) {
break;
}
}
echo $string_1;
echo "<br>\n";
echo $string_2;
it generate two unique strings:
qsBDs4JOoVRfFxyLAOGECYIsWvpcpMzAO9pypwxsqPKeAmYLOi
Ti3kE1WfGgTNxQVXtbNNbhhvvapnaUfGMVJecHkUjHbuCb85pF
Hope this is what you are looking for...
Scott, yes you are very write and good solution! Thanks.
I am also required to generate unique API token for my each user. Following is my approach, i used user information (Userid and Username):
public function generateUniqueToken($userid, $username){
$rand = mt_rand(100,999);
$md5 = md5($userid.'!(&^ 532567_465 ///'.$username);
$md53 = substr($md5,0,3);
$md5_remaining = substr($md5,3);
$md5 = $md53. $rand. $userid. $md5_remaining;
return $md5;
}
Please have a look and let me know if any improvement i can do. Thanks
Here is what I'm using on one of my projects, it's working great and it generates a UNIQUE RANDOM TOKEN:
$timestampz=time();
function generateRandomString($length = 60) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
$tokenparta = generateRandomString();
$token = $timestampz*3 . $tokenparta;
echo $token;
Please note that I multiplied the timestamp by three to create a confusion for whoever user might be wondering how this token is generated ;)
I hope it helps :)
I think this is the best method to use.
str_shuffle(md5(rand(0,100000)))
Here is a fun one
public function randomStr($length = 16) {
$string = '';
while (($len = strlen($string)) < $length) {
$size = $length - $len;
$bytes = random_bytes($size);
$string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
}
return $string;
}
Stolen from laravel here
I believe the problem with all the existing ideas is that they are probably unique, but not definitely unique (as pointed out in Dariusz Walczak's reply to loletech). I have a solution that actually is unique. It requires that your script have some sort of memory. For me this is a SQL database. You could also simply write to a file somewhere. There are two implementations:
First method: have TWO fields rather than 1 that provide uniqueness. The first field is an ID number that is not random but is unique (The first ID is 1, the second 2...). If you are using SQL, just define the ID field with the AUTO_INCREMENT property. The second field is not unique but is random. This can be generated with any of the other techniques people have already mentioned. Scott's idea was good, but md5 is convenient and probably good enough for most purposes:
$random_token = md5($_SERVER['HTTP_USER_AGENT'] . time());
Second method: Basically the same idea, but initially pick a maximum number of strings that will ever be generated. This could just be a really big number like a trillion. Then do the same thing, generate an ID, but zero pad it so that all IDs are the same number of digits. Then just concatenate the ID with the random string. It will be random enough for most purposes, but the ID section will ensure that it is also unique.
How would it be possible to generate a random, unique string using numbers and letters for use in a verify link? Like when you create an account on a website, and it sends you an email with a link, and you have to click that link in order to verify your account
How can I generate one of those using PHP?
PHP 7 standard library provides the random_bytes($length) function that generate cryptographically secure pseudo-random bytes.
Example:
$bytes = random_bytes(20);
var_dump(bin2hex($bytes));
The above example will output something similar to:
string(40) "5fe69c95ed70a9869d9f9af7d8400a6673bb9ce9"
More info: http://php.net/manual/en/function.random-bytes.php
PHP 5 (outdated)
I was just looking into how to solve this same problem, but I also want my function to create a token that can be used for password retrieval as well. This means that I need to limit the ability of the token to be guessed. Because uniqid is based on the time, and according to php.net "the return value is little different from microtime()", uniqid does not meet the criteria. PHP recommends using openssl_random_pseudo_bytes() instead to generate cryptographically secure tokens.
A quick, short and to the point answer is:
bin2hex(openssl_random_pseudo_bytes($bytes))
which will generate a random string of alphanumeric characters of length = $bytes * 2. Unfortunately this only has an alphabet of [a-f][0-9], but it works.
Below is the strongest function I could make that satisfies the criteria (This is an implemented version of Erik's answer).
function crypto_rand_secure($min, $max)
{
$range = $max - $min;
if ($range < 1) return $min; // not so random...
$log = ceil(log($range, 2));
$bytes = (int) ($log / 8) + 1; // length in bytes
$bits = (int) $log + 1; // length in bits
$filter = (int) (1 << $bits) - 1; // set all lower bits to 1
do {
$rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
$rnd = $rnd & $filter; // discard irrelevant bits
} while ($rnd > $range);
return $min + $rnd;
}
function getToken($length)
{
$token = "";
$codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
$codeAlphabet.= "0123456789";
$max = strlen($codeAlphabet); // edited
for ($i=0; $i < $length; $i++) {
$token .= $codeAlphabet[crypto_rand_secure(0, $max-1)];
}
return $token;
}
crypto_rand_secure($min, $max) works as a drop in replacement for rand() or mt_rand. It uses openssl_random_pseudo_bytes to help create a random number between $min and $max.
getToken($length) creates an alphabet to use within the token and then creates a string of length $length.
Source: http://us1.php.net/manual/en/function.openssl-random-pseudo-bytes.php#104322
Security Notice: This solution should not be used in situations where the quality of your randomness can affect the security of an application. In particular, rand() and uniqid() are not cryptographically secure random number generators. See Scott's answer for a secure alternative.
If you do not need it to be absolutely unique over time:
md5(uniqid(rand(), true))
Otherwise (given you have already determined a unique login for your user):
md5(uniqid($your_user_login, true))
Object-oriented version of the most up-voted solution
I've created an object-oriented solution based on Scott's answer:
<?php
namespace Utils;
/**
* Class RandomStringGenerator
* #package Utils
*
* Solution taken from here:
* http://stackoverflow.com/a/13733588/1056679
*/
class RandomStringGenerator
{
/** #var string */
protected $alphabet;
/** #var int */
protected $alphabetLength;
/**
* #param string $alphabet
*/
public function __construct($alphabet = '')
{
if ('' !== $alphabet) {
$this->setAlphabet($alphabet);
} else {
$this->setAlphabet(
implode(range('a', 'z'))
. implode(range('A', 'Z'))
. implode(range(0, 9))
);
}
}
/**
* #param string $alphabet
*/
public function setAlphabet($alphabet)
{
$this->alphabet = $alphabet;
$this->alphabetLength = strlen($alphabet);
}
/**
* #param int $length
* #return string
*/
public function generate($length)
{
$token = '';
for ($i = 0; $i < $length; $i++) {
$randomKey = $this->getRandomInteger(0, $this->alphabetLength);
$token .= $this->alphabet[$randomKey];
}
return $token;
}
/**
* #param int $min
* #param int $max
* #return int
*/
protected function getRandomInteger($min, $max)
{
$range = ($max - $min);
if ($range < 0) {
// Not so random...
return $min;
}
$log = log($range, 2);
// Length in bytes.
$bytes = (int) ($log / 8) + 1;
// Length in bits.
$bits = (int) $log + 1;
// Set all lower bits to 1.
$filter = (int) (1 << $bits) - 1;
do {
$rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
// Discard irrelevant bits.
$rnd = $rnd & $filter;
} while ($rnd >= $range);
return ($min + $rnd);
}
}
Usage
<?php
use Utils\RandomStringGenerator;
// Create new instance of generator class.
$generator = new RandomStringGenerator;
// Set token length.
$tokenLength = 32;
// Call method to generate random string.
$token = $generator->generate($tokenLength);
Custom alphabet
You can use custom alphabet if required.
Just pass a string with supported chars to the constructor or setter:
<?php
$customAlphabet = '0123456789ABCDEF';
// Set initial alphabet.
$generator = new RandomStringGenerator($customAlphabet);
// Change alphabet whenever needed.
$generator->setAlphabet($customAlphabet);
Here's the output samples
SRniGU2sRQb2K1ylXKnWwZr4HrtdRgrM
q1sRUjNq1K9rG905aneFzyD5IcqD4dlC
I0euIWffrURLKCCJZ5PQFcNUCto6cQfD
AKwPJMEM5ytgJyJyGqoD5FQwxv82YvMr
duoRF6gAawNOEQRICnOUNYmStWmOpEgS
sdHUkEn4565AJoTtkc8EqJ6cC4MLEHUx
eVywMdYXczuZmHaJ50nIVQjOidEVkVna
baJGt7cdLDbIxMctLsEBWgAw5BByP5V0
iqT0B2obq3oerbeXkDVLjZrrLheW4d8f
OUQYCny6tj2TYDlTuu1KsnUyaLkeObwa
I hope it will help someone. Cheers!
I'm here with some good research data based on the functions provided by Scott's answer. So I set up a Digital Ocean droplet just for this 5-day long automated test and stored the generated unique strings in a MySQL database.
During this test period, I used 5 different lengths (5, 10, 15, 20, 50) and +/-0.5 million records were inserted for each length. During my test, only the length 5 generated +/-3K duplicates out of 0.5 million and the remaining lengths didn't generate any duplicates. So we can say that if we use a length of 15 or above with Scott's functions, then we can generate highly reliable unique strings. Here is the table showing my research data:
Update
I created a simple Heroku app using these functions that returns the token as a JSON response. The app can be accessed at https://uniquestrings.herokuapp.com/api/token?length=15
You can use UUID(Universally Unique Identifier), it can be used for any purpose, from user authentication string to payment transaction id.
A UUID is a 16-octet (128-bit) number. In its canonical form, a UUID is represented by 32 hexadecimal digits, displayed in five groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 alphanumeric characters and four hyphens).
function generate_uuid() {
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
mt_rand( 0, 0xffff ),
mt_rand( 0, 0x0C2f ) | 0x4000,
mt_rand( 0, 0x3fff ) | 0x8000,
mt_rand( 0, 0x2Aff ), mt_rand( 0, 0xffD3 ), mt_rand( 0, 0xff4B )
);
}
//calling funtion
$transationID = generate_uuid();
some example outputs will be like:
E302D66D-87E3-4450-8CB6-17531895BF14
22D288BC-7289-442B-BEEA-286777D559F2
51B4DE29-3B71-4FD2-9E6C-071703E1FF31
3777C8C6-9FF5-4C78-AAA2-08A47F555E81
54B91C72-2CF4-4501-A6E9-02A60DCBAE4C
60F75C7C-1AE3-417B-82C8-14D456542CD7
8DE0168D-01D3-4502-9E59-10D665CEBCB2
hope it helps someone in future :)
This function will generate a random key using numbers and letters:
function random_string($length) {
$key = '';
$keys = array_merge(range(0, 9), range('a', 'z'));
for ($i = 0; $i < $length; $i++) {
$key .= $keys[array_rand($keys)];
}
return $key;
}
echo random_string(50);
Example output:
zsd16xzv3jsytnp87tk7ygv73k8zmr0ekh6ly7mxaeyeh46oe8
I use this one-liner:
base64_encode(openssl_random_pseudo_bytes(3 * ($length >> 2)));
where length is the length of the desired string (divisible by 4, otherwise it gets rounded down to the nearest number divisible by 4)
Use the code below to generate the random number of 11 characters or change the number as per your requirement.
$randomNum=substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyz"), 0, 11);
or we can use custom function to generate the random number
function randomNumber($length){
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $length;$i++)
$digits .= $numbers[$i];
return $digits;
}
//generate random number
$randomNum=randomNumber(11);
Generate a random number using
your favourite random-number
generator
Multiply and divide it
to get a number matching the number
of characters in your code alphabet
Get the item at that index in
your code alphabet.
Repeat from 1) until you have the length you
want
e.g (in pseudo code)
int myInt = random(0, numcharacters)
char[] codealphabet = 'ABCDEF12345'
char random = codealphabet[i]
repeat until long enough
For really random strings, you can use
<?php
echo md5(microtime(true).mt_Rand());
outputs :
40a29479ec808ad4bcff288a48a25d5c
so even if you try to generate string multiple times at exact same time, you will get different output.
This is a simple function that allows you to generate random strings containing Letters and Numbers (alphanumeric). You can also limit the string length.
These random strings can be used for various purposes, including: Referral Code, Promotional Code, Coupon Code.
Function relies on following PHP functions:
base_convert, sha1, uniqid, mt_rand
function random_code($length)
{
return substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, $length);
}
echo random_code(6);
/*sample output
* a7d9e8
* 3klo93
*/
When trying to generate a random password you are trying to :
First generate a cryptographically secure set of random bytes
Second is turning those random bytes into a printable string
Now, there are multiple way to generate random bytes in php like :
$length = 32;
//PHP 7+
$bytes= random_bytes($length);
//PHP < 7
$bytes= openssl_random_pseudo_bytes($length);
Then you want to turn these random bytes into a printable string :
You can use bin2hex :
$string = bin2hex($bytes);
or base64_encode :
$string = base64_encode($bytes);
However, note that you do not control the length of the string if you use base64.
You can use bin2hex to do that, using 32 bytes will turn into a 64 char string.
But it will only work like so in an EVEN string.
So basically you can just do :
$length = 32;
if(PHP_VERSION>=7){
$bytes= random_bytes($length);
}else{
$bytes= openssl_random_pseudo_bytes($length);
}
$string = bin2hex($bytes);
Here is what I use:
md5(time() . rand());
// Creates something like 0c947c3b1047334f5bb8a3b7adc1d97b
This people choking on a glass of water...
$random= substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ*.-_"), 0, 10);
Simple.
The posibility to this random string repeat is 0,000000000000000000000000000001^70
Here is ultimate unique id generator for you. made by me.
<?php
$d=date ("d");
$m=date ("m");
$y=date ("Y");
$t=time();
$dmt=$d+$m+$y+$t;
$ran= rand(0,10000000);
$dmtran= $dmt+$ran;
$un= uniqid();
$dmtun = $dmt.$un;
$mdun = md5($dmtran.$un);
$sort=substr($mdun, 16); // if you want sort length code.
echo $mdun;
?>
you can echo any 'var' for your id as you like. but $mdun is better, you can replace md5 to sha1 for better code but that will be very long which may you dont need.
Thank you.
I like to use hash keys when dealing verification links. I would recommend using the microtime and hashing that using MD5 since there should be no reason why the keys should be the same since it hashes based off of the microtime.
$key = md5(rand());
$key = md5(microtime());
function random_string($length = 8) {
$alphabets = range('A','Z');
$numbers = range('0','9');
$additional_characters = array('_','=');
$final_array = array_merge($alphabets,$numbers,$additional_characters);
while($length--) {
$key = array_rand($final_array);
$password .= $final_array[$key];
}
if (preg_match('/[A-Za-z0-9]/', $password))
{
return $password;
}else{
return random_string();
}
}
Simple 'one line' string hash generator like
77zd43-7bc495-64cg9a-535548 (1byte = 2chars)
$hash = implode('-', [
bin2hex(random_bytes(3)),
bin2hex(random_bytes(3)),
bin2hex(random_bytes(3)),
bin2hex(random_bytes(3)),
]);
after reading previous examples I came up with this:
protected static $nonce_length = 32;
public static function getNonce()
{
$chars = array();
for ($i = 0; $i < 10; $i++)
$chars = array_merge($chars, range(0, 9), range('A', 'Z'));
shuffle($chars);
$start = mt_rand(0, count($chars) - self::$nonce_length);
return substr(join('', $chars), $start, self::$nonce_length);
}
I duplicate 10 times the array[0-9,A-Z] and shuffle the elements, after I get a random start point for substr() to be more 'creative' :)
you can add [a-z] and other elements to array, duplicate more or less, be more creative than me
<?php
function generateRandomString($length = 11) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
?>
above function will generate you a random string which is length of 11 characters.
If you want to generate a unique string in PHP, try following.
md5(uniqid().mt_rand());
In this,
uniqid() - It will generate unique string. This function returns timestamp based unique identifier as a string.
mt_rand() - Generate random number.
md5() - It will generate the hash string.
A simple solution is to convert base 64 to alphanumeric by discarding the non-alphanumeric characters.
This one uses random_bytes() for a cryptographically secure result.
function random_alphanumeric(int $length): string
{
$result='';
do
{
//Base 64 produces 4 characters for each 3 bytes, so most times this will give enough bytes in a single pass
$bytes=random_bytes(($length+3-strlen($result))*2);
//Discard non-alhpanumeric characters
$result.=str_replace(['/','+','='],['','',''],base64_encode($bytes));
//Keep adding characters until the string is long enough
//Add a few extra because the last 2 or 3 characters of a base 64 string tend to be less diverse
}while(strlen($result)<$length+3);
return substr($result,0,$length);
}
Edit: I just revisited this because I need something a bit more flexible. Here is a solution that performs a bit better than the above and gives the option to specify any subset of the ASCII character set:
<?php
class RandomText
{
protected
$allowedChars,
//Maximum index to use
$allowedCount,
//Index values will be taken from a pool of this size
//It is a power of 2 to keep the distribution of values even
$distributionSize,
//This many characters will be generated for each output character
$ratio;
/**
* #param string $allowedChars characters to choose from
*/
public function __construct(string $allowedChars)
{
$this->allowedCount = strlen($allowedChars);
if($this->allowedCount < 1 || $this->allowedCount > 256) throw new \Exception('At least 1 and no more than 256 allowed character(s) must be specified.');
$this->allowedChars = $allowedChars;
//Find the power of 2 equal or greater than the number of allowed characters
$this->distributionSize = pow(2,ceil(log($this->allowedCount, 2)));
//Generating random bytes is the expensive part of this algorithm
//In most cases some will be wasted so it is helpful to produce some extras, but not too many
//On average, this is how many characters needed to produce 1 character in the allowed set
//50% of the time, more characters will be needed. My tests have shown this to perform well.
$this->ratio = $this->distributionSize / $this->allowedCount;
}
/**
* #param int $length string length of required result
* #return string random text
*/
public function get(int $length) : string
{
if($length < 1) throw new \Exception('$length must be >= 1.');
$result = '';
//Keep track of result length to prevent having to compute strlen()
$l = 0;
$indices = null;
$i = null;
do
{
//Bytes will be used to index the character set. Convert to integers.
$indices = unpack('C*', random_bytes(ceil(($length - $l) * $this->ratio)));
foreach($indices as $i)
{
//Reduce to the smallest range that gives an even distribution
$i %= $this->distributionSize;
//If the index is within the range of characters, add one char to the string
if($i < $this->allowedCount)
{
$l++;
$result .= $this->allowedChars[$i];
}
if($l >= $length) break;
}
}while($l < $length);
return $result;
}
}
one can use this code. i tested with 35,000,00 IDs no duplicates.
<?php
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_';
$result = '';
for ($i = 0; $i < 11; $i++)
$result .= $characters[mt_rand(0, 63)];?>
you are free to modify it as your need. and if you have any suggestions feel free to comment.it is recommended that you should check every id in your database before using this ids by doing that you have 100% unique ids in your database.
function codeGenerate() {
$randCode = (string)mt_rand(1000,9999);
$randChar = rand(65,90);
$randInx = rand(0,3);
$randCode[$randInx] = chr($randChar);
return $randCode;
}
echo codeGenerate();
OUTPUT
38I7
33V7
E836
736U
I always use this my function to generate a custom random alphanumeric string... Hope this help.
<?php
function random_alphanumeric($length) {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12345689';
$my_string = '';
for ($i = 0; $i < $length; $i++) {
$pos = random_int(0, strlen($chars) -1);
$my_string .= substr($chars, $pos, 1);
}
return $my_string;
}
echo random_alphanumeric(50); // 50 characters
?>
It generates for example: Y1FypdjVbFCFK6Gh9FDJpe6dciwJEfV6MQGpJqAfuijaYSZ86g
If you want compare with another string to be sure that is a unique sequence you can use this trick...
$string_1 = random_alphanumeric(50);
$string_2 = random_alphanumeric(50);
while ($string_1 == $string_2) {
$string_1 = random_alphanumeric(50);
$string_2 = random_alphanumeric(50);
if ($string_1 != $string_2) {
break;
}
}
echo $string_1;
echo "<br>\n";
echo $string_2;
it generate two unique strings:
qsBDs4JOoVRfFxyLAOGECYIsWvpcpMzAO9pypwxsqPKeAmYLOi
Ti3kE1WfGgTNxQVXtbNNbhhvvapnaUfGMVJecHkUjHbuCb85pF
Hope this is what you are looking for...
Scott, yes you are very write and good solution! Thanks.
I am also required to generate unique API token for my each user. Following is my approach, i used user information (Userid and Username):
public function generateUniqueToken($userid, $username){
$rand = mt_rand(100,999);
$md5 = md5($userid.'!(&^ 532567_465 ///'.$username);
$md53 = substr($md5,0,3);
$md5_remaining = substr($md5,3);
$md5 = $md53. $rand. $userid. $md5_remaining;
return $md5;
}
Please have a look and let me know if any improvement i can do. Thanks
Here is what I'm using on one of my projects, it's working great and it generates a UNIQUE RANDOM TOKEN:
$timestampz=time();
function generateRandomString($length = 60) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
$tokenparta = generateRandomString();
$token = $timestampz*3 . $tokenparta;
echo $token;
Please note that I multiplied the timestamp by three to create a confusion for whoever user might be wondering how this token is generated ;)
I hope it helps :)
I think this is the best method to use.
str_shuffle(md5(rand(0,100000)))
Here is a fun one
public function randomStr($length = 16) {
$string = '';
while (($len = strlen($string)) < $length) {
$size = $length - $len;
$bytes = random_bytes($size);
$string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
}
return $string;
}
Stolen from laravel here
I believe the problem with all the existing ideas is that they are probably unique, but not definitely unique (as pointed out in Dariusz Walczak's reply to loletech). I have a solution that actually is unique. It requires that your script have some sort of memory. For me this is a SQL database. You could also simply write to a file somewhere. There are two implementations:
First method: have TWO fields rather than 1 that provide uniqueness. The first field is an ID number that is not random but is unique (The first ID is 1, the second 2...). If you are using SQL, just define the ID field with the AUTO_INCREMENT property. The second field is not unique but is random. This can be generated with any of the other techniques people have already mentioned. Scott's idea was good, but md5 is convenient and probably good enough for most purposes:
$random_token = md5($_SERVER['HTTP_USER_AGENT'] . time());
Second method: Basically the same idea, but initially pick a maximum number of strings that will ever be generated. This could just be a really big number like a trillion. Then do the same thing, generate an ID, but zero pad it so that all IDs are the same number of digits. Then just concatenate the ID with the random string. It will be random enough for most purposes, but the ID section will ensure that it is also unique.
How would it be possible to generate a random, unique string using numbers and letters for use in a verify link? Like when you create an account on a website, and it sends you an email with a link, and you have to click that link in order to verify your account
How can I generate one of those using PHP?
PHP 7 standard library provides the random_bytes($length) function that generate cryptographically secure pseudo-random bytes.
Example:
$bytes = random_bytes(20);
var_dump(bin2hex($bytes));
The above example will output something similar to:
string(40) "5fe69c95ed70a9869d9f9af7d8400a6673bb9ce9"
More info: http://php.net/manual/en/function.random-bytes.php
PHP 5 (outdated)
I was just looking into how to solve this same problem, but I also want my function to create a token that can be used for password retrieval as well. This means that I need to limit the ability of the token to be guessed. Because uniqid is based on the time, and according to php.net "the return value is little different from microtime()", uniqid does not meet the criteria. PHP recommends using openssl_random_pseudo_bytes() instead to generate cryptographically secure tokens.
A quick, short and to the point answer is:
bin2hex(openssl_random_pseudo_bytes($bytes))
which will generate a random string of alphanumeric characters of length = $bytes * 2. Unfortunately this only has an alphabet of [a-f][0-9], but it works.
Below is the strongest function I could make that satisfies the criteria (This is an implemented version of Erik's answer).
function crypto_rand_secure($min, $max)
{
$range = $max - $min;
if ($range < 1) return $min; // not so random...
$log = ceil(log($range, 2));
$bytes = (int) ($log / 8) + 1; // length in bytes
$bits = (int) $log + 1; // length in bits
$filter = (int) (1 << $bits) - 1; // set all lower bits to 1
do {
$rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
$rnd = $rnd & $filter; // discard irrelevant bits
} while ($rnd > $range);
return $min + $rnd;
}
function getToken($length)
{
$token = "";
$codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
$codeAlphabet.= "0123456789";
$max = strlen($codeAlphabet); // edited
for ($i=0; $i < $length; $i++) {
$token .= $codeAlphabet[crypto_rand_secure(0, $max-1)];
}
return $token;
}
crypto_rand_secure($min, $max) works as a drop in replacement for rand() or mt_rand. It uses openssl_random_pseudo_bytes to help create a random number between $min and $max.
getToken($length) creates an alphabet to use within the token and then creates a string of length $length.
Source: http://us1.php.net/manual/en/function.openssl-random-pseudo-bytes.php#104322
Security Notice: This solution should not be used in situations where the quality of your randomness can affect the security of an application. In particular, rand() and uniqid() are not cryptographically secure random number generators. See Scott's answer for a secure alternative.
If you do not need it to be absolutely unique over time:
md5(uniqid(rand(), true))
Otherwise (given you have already determined a unique login for your user):
md5(uniqid($your_user_login, true))
Object-oriented version of the most up-voted solution
I've created an object-oriented solution based on Scott's answer:
<?php
namespace Utils;
/**
* Class RandomStringGenerator
* #package Utils
*
* Solution taken from here:
* http://stackoverflow.com/a/13733588/1056679
*/
class RandomStringGenerator
{
/** #var string */
protected $alphabet;
/** #var int */
protected $alphabetLength;
/**
* #param string $alphabet
*/
public function __construct($alphabet = '')
{
if ('' !== $alphabet) {
$this->setAlphabet($alphabet);
} else {
$this->setAlphabet(
implode(range('a', 'z'))
. implode(range('A', 'Z'))
. implode(range(0, 9))
);
}
}
/**
* #param string $alphabet
*/
public function setAlphabet($alphabet)
{
$this->alphabet = $alphabet;
$this->alphabetLength = strlen($alphabet);
}
/**
* #param int $length
* #return string
*/
public function generate($length)
{
$token = '';
for ($i = 0; $i < $length; $i++) {
$randomKey = $this->getRandomInteger(0, $this->alphabetLength);
$token .= $this->alphabet[$randomKey];
}
return $token;
}
/**
* #param int $min
* #param int $max
* #return int
*/
protected function getRandomInteger($min, $max)
{
$range = ($max - $min);
if ($range < 0) {
// Not so random...
return $min;
}
$log = log($range, 2);
// Length in bytes.
$bytes = (int) ($log / 8) + 1;
// Length in bits.
$bits = (int) $log + 1;
// Set all lower bits to 1.
$filter = (int) (1 << $bits) - 1;
do {
$rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
// Discard irrelevant bits.
$rnd = $rnd & $filter;
} while ($rnd >= $range);
return ($min + $rnd);
}
}
Usage
<?php
use Utils\RandomStringGenerator;
// Create new instance of generator class.
$generator = new RandomStringGenerator;
// Set token length.
$tokenLength = 32;
// Call method to generate random string.
$token = $generator->generate($tokenLength);
Custom alphabet
You can use custom alphabet if required.
Just pass a string with supported chars to the constructor or setter:
<?php
$customAlphabet = '0123456789ABCDEF';
// Set initial alphabet.
$generator = new RandomStringGenerator($customAlphabet);
// Change alphabet whenever needed.
$generator->setAlphabet($customAlphabet);
Here's the output samples
SRniGU2sRQb2K1ylXKnWwZr4HrtdRgrM
q1sRUjNq1K9rG905aneFzyD5IcqD4dlC
I0euIWffrURLKCCJZ5PQFcNUCto6cQfD
AKwPJMEM5ytgJyJyGqoD5FQwxv82YvMr
duoRF6gAawNOEQRICnOUNYmStWmOpEgS
sdHUkEn4565AJoTtkc8EqJ6cC4MLEHUx
eVywMdYXczuZmHaJ50nIVQjOidEVkVna
baJGt7cdLDbIxMctLsEBWgAw5BByP5V0
iqT0B2obq3oerbeXkDVLjZrrLheW4d8f
OUQYCny6tj2TYDlTuu1KsnUyaLkeObwa
I hope it will help someone. Cheers!
I'm here with some good research data based on the functions provided by Scott's answer. So I set up a Digital Ocean droplet just for this 5-day long automated test and stored the generated unique strings in a MySQL database.
During this test period, I used 5 different lengths (5, 10, 15, 20, 50) and +/-0.5 million records were inserted for each length. During my test, only the length 5 generated +/-3K duplicates out of 0.5 million and the remaining lengths didn't generate any duplicates. So we can say that if we use a length of 15 or above with Scott's functions, then we can generate highly reliable unique strings. Here is the table showing my research data:
Update
I created a simple Heroku app using these functions that returns the token as a JSON response. The app can be accessed at https://uniquestrings.herokuapp.com/api/token?length=15
You can use UUID(Universally Unique Identifier), it can be used for any purpose, from user authentication string to payment transaction id.
A UUID is a 16-octet (128-bit) number. In its canonical form, a UUID is represented by 32 hexadecimal digits, displayed in five groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 alphanumeric characters and four hyphens).
function generate_uuid() {
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
mt_rand( 0, 0xffff ),
mt_rand( 0, 0x0C2f ) | 0x4000,
mt_rand( 0, 0x3fff ) | 0x8000,
mt_rand( 0, 0x2Aff ), mt_rand( 0, 0xffD3 ), mt_rand( 0, 0xff4B )
);
}
//calling funtion
$transationID = generate_uuid();
some example outputs will be like:
E302D66D-87E3-4450-8CB6-17531895BF14
22D288BC-7289-442B-BEEA-286777D559F2
51B4DE29-3B71-4FD2-9E6C-071703E1FF31
3777C8C6-9FF5-4C78-AAA2-08A47F555E81
54B91C72-2CF4-4501-A6E9-02A60DCBAE4C
60F75C7C-1AE3-417B-82C8-14D456542CD7
8DE0168D-01D3-4502-9E59-10D665CEBCB2
hope it helps someone in future :)
This function will generate a random key using numbers and letters:
function random_string($length) {
$key = '';
$keys = array_merge(range(0, 9), range('a', 'z'));
for ($i = 0; $i < $length; $i++) {
$key .= $keys[array_rand($keys)];
}
return $key;
}
echo random_string(50);
Example output:
zsd16xzv3jsytnp87tk7ygv73k8zmr0ekh6ly7mxaeyeh46oe8
I use this one-liner:
base64_encode(openssl_random_pseudo_bytes(3 * ($length >> 2)));
where length is the length of the desired string (divisible by 4, otherwise it gets rounded down to the nearest number divisible by 4)
Use the code below to generate the random number of 11 characters or change the number as per your requirement.
$randomNum=substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyz"), 0, 11);
or we can use custom function to generate the random number
function randomNumber($length){
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $length;$i++)
$digits .= $numbers[$i];
return $digits;
}
//generate random number
$randomNum=randomNumber(11);
Generate a random number using
your favourite random-number
generator
Multiply and divide it
to get a number matching the number
of characters in your code alphabet
Get the item at that index in
your code alphabet.
Repeat from 1) until you have the length you
want
e.g (in pseudo code)
int myInt = random(0, numcharacters)
char[] codealphabet = 'ABCDEF12345'
char random = codealphabet[i]
repeat until long enough
For really random strings, you can use
<?php
echo md5(microtime(true).mt_Rand());
outputs :
40a29479ec808ad4bcff288a48a25d5c
so even if you try to generate string multiple times at exact same time, you will get different output.
This is a simple function that allows you to generate random strings containing Letters and Numbers (alphanumeric). You can also limit the string length.
These random strings can be used for various purposes, including: Referral Code, Promotional Code, Coupon Code.
Function relies on following PHP functions:
base_convert, sha1, uniqid, mt_rand
function random_code($length)
{
return substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, $length);
}
echo random_code(6);
/*sample output
* a7d9e8
* 3klo93
*/
When trying to generate a random password you are trying to :
First generate a cryptographically secure set of random bytes
Second is turning those random bytes into a printable string
Now, there are multiple way to generate random bytes in php like :
$length = 32;
//PHP 7+
$bytes= random_bytes($length);
//PHP < 7
$bytes= openssl_random_pseudo_bytes($length);
Then you want to turn these random bytes into a printable string :
You can use bin2hex :
$string = bin2hex($bytes);
or base64_encode :
$string = base64_encode($bytes);
However, note that you do not control the length of the string if you use base64.
You can use bin2hex to do that, using 32 bytes will turn into a 64 char string.
But it will only work like so in an EVEN string.
So basically you can just do :
$length = 32;
if(PHP_VERSION>=7){
$bytes= random_bytes($length);
}else{
$bytes= openssl_random_pseudo_bytes($length);
}
$string = bin2hex($bytes);
Here is what I use:
md5(time() . rand());
// Creates something like 0c947c3b1047334f5bb8a3b7adc1d97b
This people choking on a glass of water...
$random= substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ*.-_"), 0, 10);
Simple.
The posibility to this random string repeat is 0,000000000000000000000000000001^70
Here is ultimate unique id generator for you. made by me.
<?php
$d=date ("d");
$m=date ("m");
$y=date ("Y");
$t=time();
$dmt=$d+$m+$y+$t;
$ran= rand(0,10000000);
$dmtran= $dmt+$ran;
$un= uniqid();
$dmtun = $dmt.$un;
$mdun = md5($dmtran.$un);
$sort=substr($mdun, 16); // if you want sort length code.
echo $mdun;
?>
you can echo any 'var' for your id as you like. but $mdun is better, you can replace md5 to sha1 for better code but that will be very long which may you dont need.
Thank you.
I like to use hash keys when dealing verification links. I would recommend using the microtime and hashing that using MD5 since there should be no reason why the keys should be the same since it hashes based off of the microtime.
$key = md5(rand());
$key = md5(microtime());
function random_string($length = 8) {
$alphabets = range('A','Z');
$numbers = range('0','9');
$additional_characters = array('_','=');
$final_array = array_merge($alphabets,$numbers,$additional_characters);
while($length--) {
$key = array_rand($final_array);
$password .= $final_array[$key];
}
if (preg_match('/[A-Za-z0-9]/', $password))
{
return $password;
}else{
return random_string();
}
}
Simple 'one line' string hash generator like
77zd43-7bc495-64cg9a-535548 (1byte = 2chars)
$hash = implode('-', [
bin2hex(random_bytes(3)),
bin2hex(random_bytes(3)),
bin2hex(random_bytes(3)),
bin2hex(random_bytes(3)),
]);
after reading previous examples I came up with this:
protected static $nonce_length = 32;
public static function getNonce()
{
$chars = array();
for ($i = 0; $i < 10; $i++)
$chars = array_merge($chars, range(0, 9), range('A', 'Z'));
shuffle($chars);
$start = mt_rand(0, count($chars) - self::$nonce_length);
return substr(join('', $chars), $start, self::$nonce_length);
}
I duplicate 10 times the array[0-9,A-Z] and shuffle the elements, after I get a random start point for substr() to be more 'creative' :)
you can add [a-z] and other elements to array, duplicate more or less, be more creative than me
<?php
function generateRandomString($length = 11) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
?>
above function will generate you a random string which is length of 11 characters.
If you want to generate a unique string in PHP, try following.
md5(uniqid().mt_rand());
In this,
uniqid() - It will generate unique string. This function returns timestamp based unique identifier as a string.
mt_rand() - Generate random number.
md5() - It will generate the hash string.
A simple solution is to convert base 64 to alphanumeric by discarding the non-alphanumeric characters.
This one uses random_bytes() for a cryptographically secure result.
function random_alphanumeric(int $length): string
{
$result='';
do
{
//Base 64 produces 4 characters for each 3 bytes, so most times this will give enough bytes in a single pass
$bytes=random_bytes(($length+3-strlen($result))*2);
//Discard non-alhpanumeric characters
$result.=str_replace(['/','+','='],['','',''],base64_encode($bytes));
//Keep adding characters until the string is long enough
//Add a few extra because the last 2 or 3 characters of a base 64 string tend to be less diverse
}while(strlen($result)<$length+3);
return substr($result,0,$length);
}
Edit: I just revisited this because I need something a bit more flexible. Here is a solution that performs a bit better than the above and gives the option to specify any subset of the ASCII character set:
<?php
class RandomText
{
protected
$allowedChars,
//Maximum index to use
$allowedCount,
//Index values will be taken from a pool of this size
//It is a power of 2 to keep the distribution of values even
$distributionSize,
//This many characters will be generated for each output character
$ratio;
/**
* #param string $allowedChars characters to choose from
*/
public function __construct(string $allowedChars)
{
$this->allowedCount = strlen($allowedChars);
if($this->allowedCount < 1 || $this->allowedCount > 256) throw new \Exception('At least 1 and no more than 256 allowed character(s) must be specified.');
$this->allowedChars = $allowedChars;
//Find the power of 2 equal or greater than the number of allowed characters
$this->distributionSize = pow(2,ceil(log($this->allowedCount, 2)));
//Generating random bytes is the expensive part of this algorithm
//In most cases some will be wasted so it is helpful to produce some extras, but not too many
//On average, this is how many characters needed to produce 1 character in the allowed set
//50% of the time, more characters will be needed. My tests have shown this to perform well.
$this->ratio = $this->distributionSize / $this->allowedCount;
}
/**
* #param int $length string length of required result
* #return string random text
*/
public function get(int $length) : string
{
if($length < 1) throw new \Exception('$length must be >= 1.');
$result = '';
//Keep track of result length to prevent having to compute strlen()
$l = 0;
$indices = null;
$i = null;
do
{
//Bytes will be used to index the character set. Convert to integers.
$indices = unpack('C*', random_bytes(ceil(($length - $l) * $this->ratio)));
foreach($indices as $i)
{
//Reduce to the smallest range that gives an even distribution
$i %= $this->distributionSize;
//If the index is within the range of characters, add one char to the string
if($i < $this->allowedCount)
{
$l++;
$result .= $this->allowedChars[$i];
}
if($l >= $length) break;
}
}while($l < $length);
return $result;
}
}
one can use this code. i tested with 35,000,00 IDs no duplicates.
<?php
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_';
$result = '';
for ($i = 0; $i < 11; $i++)
$result .= $characters[mt_rand(0, 63)];?>
you are free to modify it as your need. and if you have any suggestions feel free to comment.it is recommended that you should check every id in your database before using this ids by doing that you have 100% unique ids in your database.
function codeGenerate() {
$randCode = (string)mt_rand(1000,9999);
$randChar = rand(65,90);
$randInx = rand(0,3);
$randCode[$randInx] = chr($randChar);
return $randCode;
}
echo codeGenerate();
OUTPUT
38I7
33V7
E836
736U
I always use this my function to generate a custom random alphanumeric string... Hope this help.
<?php
function random_alphanumeric($length) {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12345689';
$my_string = '';
for ($i = 0; $i < $length; $i++) {
$pos = random_int(0, strlen($chars) -1);
$my_string .= substr($chars, $pos, 1);
}
return $my_string;
}
echo random_alphanumeric(50); // 50 characters
?>
It generates for example: Y1FypdjVbFCFK6Gh9FDJpe6dciwJEfV6MQGpJqAfuijaYSZ86g
If you want compare with another string to be sure that is a unique sequence you can use this trick...
$string_1 = random_alphanumeric(50);
$string_2 = random_alphanumeric(50);
while ($string_1 == $string_2) {
$string_1 = random_alphanumeric(50);
$string_2 = random_alphanumeric(50);
if ($string_1 != $string_2) {
break;
}
}
echo $string_1;
echo "<br>\n";
echo $string_2;
it generate two unique strings:
qsBDs4JOoVRfFxyLAOGECYIsWvpcpMzAO9pypwxsqPKeAmYLOi
Ti3kE1WfGgTNxQVXtbNNbhhvvapnaUfGMVJecHkUjHbuCb85pF
Hope this is what you are looking for...
Scott, yes you are very write and good solution! Thanks.
I am also required to generate unique API token for my each user. Following is my approach, i used user information (Userid and Username):
public function generateUniqueToken($userid, $username){
$rand = mt_rand(100,999);
$md5 = md5($userid.'!(&^ 532567_465 ///'.$username);
$md53 = substr($md5,0,3);
$md5_remaining = substr($md5,3);
$md5 = $md53. $rand. $userid. $md5_remaining;
return $md5;
}
Please have a look and let me know if any improvement i can do. Thanks
Here is what I'm using on one of my projects, it's working great and it generates a UNIQUE RANDOM TOKEN:
$timestampz=time();
function generateRandomString($length = 60) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
$tokenparta = generateRandomString();
$token = $timestampz*3 . $tokenparta;
echo $token;
Please note that I multiplied the timestamp by three to create a confusion for whoever user might be wondering how this token is generated ;)
I hope it helps :)
I think this is the best method to use.
str_shuffle(md5(rand(0,100000)))
Here is a fun one
public function randomStr($length = 16) {
$string = '';
while (($len = strlen($string)) < $length) {
$size = $length - $len;
$bytes = random_bytes($size);
$string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
}
return $string;
}
Stolen from laravel here
I believe the problem with all the existing ideas is that they are probably unique, but not definitely unique (as pointed out in Dariusz Walczak's reply to loletech). I have a solution that actually is unique. It requires that your script have some sort of memory. For me this is a SQL database. You could also simply write to a file somewhere. There are two implementations:
First method: have TWO fields rather than 1 that provide uniqueness. The first field is an ID number that is not random but is unique (The first ID is 1, the second 2...). If you are using SQL, just define the ID field with the AUTO_INCREMENT property. The second field is not unique but is random. This can be generated with any of the other techniques people have already mentioned. Scott's idea was good, but md5 is convenient and probably good enough for most purposes:
$random_token = md5($_SERVER['HTTP_USER_AGENT'] . time());
Second method: Basically the same idea, but initially pick a maximum number of strings that will ever be generated. This could just be a really big number like a trillion. Then do the same thing, generate an ID, but zero pad it so that all IDs are the same number of digits. Then just concatenate the ID with the random string. It will be random enough for most purposes, but the ID section will ensure that it is also unique.
I know that the rand function in PHP generates random integers, but what is the best way to generate a random string such as:
Original string, 9 chars
$string = 'abcdefghi';
Example random string limiting to 6 chars
$string = 'ibfeca';
UPDATE: I have found tons of these types of functions, basically I'm trying to understand the logic behind each step.
UPDATE: The function should generate any amount of chars as required.
Please comment the parts if you reply.
If you want to allow repetitive occurences of characters, you can use this function:
function randString($length, $charset='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')
{
$str = '';
$count = strlen($charset);
while ($length--) {
$str .= $charset[mt_rand(0, $count-1)];
}
return $str;
}
The basic algorithm is to generate <length> times a random number between 0 and <number of characters> − 1 we use as index to pick a character from our set and concatenate those characters. The 0 and <number of characters> − 1 bounds represent the bounds of the $charset string as the first character is addressed with $charset[0] and the last with $charset[count($charset) - 1].
Well, you didn't clarify all the questions I asked in my comment, but I'll assume that you want a function that can take a string of "possible" characters and a length of string to return. Commented thoroughly as requested, using more variables than I would normally, for clarity:
function get_random_string($valid_chars, $length)
{
// start with an empty random string
$random_string = "";
// count the number of chars in the valid chars string so we know how many choices we have
$num_valid_chars = strlen($valid_chars);
// repeat the steps until we've created a string of the right length
for ($i = 0; $i < $length; $i++)
{
// pick a random number from 1 up to the number of valid chars
$random_pick = mt_rand(1, $num_valid_chars);
// take the random character out of the string of valid chars
// subtract 1 from $random_pick because strings are indexed starting at 0, and we started picking at 1
$random_char = $valid_chars[$random_pick-1];
// add the randomly-chosen char onto the end of our string so far
$random_string .= $random_char;
}
// return our finished random string
return $random_string;
}
To call this function with your example data, you'd call it something like:
$original_string = 'abcdefghi';
$random_string = get_random_string($original_string, 6);
Note that this function doesn't check for uniqueness in the valid chars passed to it. For example, if you called it with a valid chars string of 'AAAB', it would be three times more likely to choose an A for each letter as a B. That could be considered a bug or a feature, depending on your needs.
My favorite:
echo substr(md5(rand()), 0, 7);
So, let me start off by saying USE A LIBRARY. Many exist:
RandomCompat
RandomLib
SecurityMultiTool
The core of the problem is almost every answer in this page is susceptible to attack. mt_rand(), rand(), lcg_value() and uniqid() are all vulnerable to attack.
A good system will use /dev/urandom from the filesystem, or mcrypt_create_iv() (with MCRYPT_DEV_URANDOM) or openssl_pseudo_random_bytes(). Which all of the above do. PHP 7 will come with two new functions random_bytes($len) and random_int($min, $max) that are also safe.
Be aware that most of those functions (except random_int()) return "raw strings" meaning they can contain any ASCII character from 0 - 255. If you want a printable string, I'd suggest running the result through base64_encode().
function generate_random_string($name_length = 8) {
$alpha_numeric = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
return substr(str_shuffle(str_repeat($alpha_numeric, $name_length)), 0, $name_length);
}
Updated the code as per mzhang's great suggestion in the comments below.
A better and updated version of #taskamiski's excellent answer:
Better version, using mt_rand() instead of rand():
echo md5(mt_rand()); // 32 char string = 128bit
Even better, for longer strings, using the hash() function that allows to select hashing algorithmns:
echo hash('sha256', mt_rand()); // 64 char string
echo hash('sha512', mt_rand()); // 128 char string
If you want to cut the result down to let's say 50 chars, do it like this:
echo substr(hash('sha256', mt_rand()), 0, 50); // 50 char string
Joining characters at the end should be more efficient that repeated string concatenation.
Edit #1: Added option to avoid character repetition.
Edit #2: Throws exception to avoid getting into infinite loop if $norepeat is selected and $len is greater than the charset to pick from.
Edit #3: Uses array keys to store picked random characters when $norepeat is selected, as associative array key lookup is faster than linearly searching the array.
function rand_str($len, $norepeat = true)
{
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$max = strlen($chars) - 1;
if ($norepeat && len > $max + 1) {
throw new Exception("Non repetitive random string can't be longer than charset");
}
$rand_chars = array();
while ($len) {
$picked = $chars[mt_rand(0, $max)];
if ($norepeat) {
if (!array_key_exists($picked, $rand_chars)) {
$rand_chars[$picked] = true;
$len--;
}
}
else {
$rand_chars[] = $picked;
$len--;
}
}
return implode('', $norepeat ? array_keys($rand_chars) : $rand_chars);
}
this will generate random string
function generateRandomString($length=10) {
$original_string = array_merge(range(0,9), range('a','z'), range('A', 'Z'));
$original_string = implode("", $original_string);
return substr(str_shuffle($original_string), 0, $length);
}
echo generateRandomString(6);
I think I will add my contribution here as well.
function random_string($length) {
$bytes_1 = openssl_random_pseudo_bytes($length);
$hex_1 = bin2hex($bytes_1);
$random_numbers = substr(sha1(rand()), 0, $length);
$bytes_2 = openssl_random_pseudo_bytes($length);
$hex_2 = bin2hex($bytes_2);
$combined_chars = $hex_1 . $random_numbers . $hex_2;
$chars_crypted = hash('sha512', $combined_chars);
return $chars_crypted;
}
Thanks
Most aspects of this have already been discussed, but i'd recommend a slight update:
If you are using this for retail usage, I would avoid the domain
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
and instead use:
ABCDEFGHJKMNPQRSTUVWXY3456789
Granted, you end up with far fewer characters, but it saves a great deal of hassle, as customers cannot mistake 0 for O, or 1 for l or 2 for Z. Also, you can do an UPPER on the input and customers can then enter upper or lower case letters -- that is also sometimes confusing since they can look similar.
What do you need a random string for?
Is this going to be used for anything remotely analogous to a password?
If your random string requires any security properties at all, you should use PHP 7's random_int() function instead of all the insecure mt_rand() answers in this thread.
/**
* Generate a random string
*
* #link https://paragonie.com/b/JvICXzh_jhLyt4y3
*
* #param int $length - How long should our random string be?
* #param string $charset - A string of all possible characters to choose from
* #return string
*/
function random_str($length = 32, $charset = 'abcdefghijklmnopqrstuvwxyz')
{
// Type checks:
if (!is_numeric($length)) {
throw new InvalidArgumentException(
'random_str - Argument 1 - expected an integer'
);
}
if (!is_string($charset)) {
throw new InvalidArgumentException(
'random_str - Argument 2 - expected a string'
);
}
if ($length < 1) {
// Just return an empty string. Any value < 1 is meaningless.
return '';
}
// This is the maximum index for all of the characters in the string $charset
$charset_max = strlen($charset) - 1;
if ($charset_max < 1) {
// Avoid letting users do: random_str($int, 'a'); -> 'aaaaa...'
throw new LogicException(
'random_str - Argument 2 - expected a string at least 2 characters long'
);
}
// Now that we have good data, this is the meat of our function:
$random_str = '';
for ($i = 0; $i < $length; ++$i) {
$r = random_int(0, $charset_max);
$random_str .= $charset[$r];
}
return $random_str;
}
If you aren't on PHP 7 yet (which is probably the case, as it hasn't been released as of this writing), then you'll want paragonie/random_compat, which is a userland implementation of random_bytes() and random_int() for PHP 5 projects.
For security contexts, always use random_int(), not rand(), mt_rand(), etc. See ircmaxell's answer as well.
built on top of https://stackoverflow.com/a/853898/533426
but with php 7 cryptographically secure random function and lower AND upper case alphabet
function random($length = 8){
$valid_chars ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
// start with an empty random string
$random_string = "";
// count the number of chars in the valid chars string so we know how many choices we have
$num_valid_chars = strlen($valid_chars);
// repeat the steps until we've created a string of the right length
for ($i = 0; $i < $length; $i++)
{
// pick a random number from 1 up to the number of valid chars
$random_pick = random_int(1, $num_valid_chars);
// take the random character out of the string of valid chars
// subtract 1 from $random_pick because strings are indexed starting at 0, and we started picking at 1
$random_char = $valid_chars[$random_pick-1];
// add the randomly-chosen char onto the end of our string so far
$random_string .= $random_char;
}
// return our finished random string
return $random_string;
}
//example output XjdXHakZ, yBG8hpZG, L6jg4FpK
// #author http://codeascraft.etsy.com/2012/07/19/better-random-numbers-in-php-using-devurandom/
function devurandom_rand($min = 0, $max = 0x7FFFFFFF)
{
$diff = $max - $min;
if ($diff < 0 || $diff > 0x7FFFFFFF) {
throw new RuntimeException('Bad range');
}
$bytes = mcrypt_create_iv(4, MCRYPT_DEV_URANDOM);
if ($bytes === false || strlen($bytes) != 4) {
throw new RuntimeException('Unable to get 4 bytes');
}
$ary = unpack('Nint', $bytes);
$val = $ary['int'] & 0x7FFFFFFF; // 32-bit safe
$fp = (float) $val / 2147483647.0; // convert to [0,1]
return round($fp * $diff) + $min;
}
function build_token($length = 60, $characters_map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {
$map_length = mb_strlen($characters_map)-1;
$token = '';
while ($length--) {
$token .= mb_substr($characters_map, devurandom_rand(0,$map_length),1);
}
return $token;
}
This will work only in UNIX environment where PHP is compiled with mcrypt.
Do you want to create your password by a random permutation of the original letters? Should it just contain unique characters?
Use rand to choose random letters by index.
This is an old question but I want try to post my solution... I always use this my function to generate a custom random alphanumeric string...
<?php
function random_alphanumeric($length) {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12345689';
$my_string = '';
for ($i = 0; $i < $length; $i++) {
$pos = mt_rand(0, strlen($chars) -1);
$my_string .= substr($chars, $pos, 1);
}
return $my_string;
}
$test = random_alphanumeric(50); // 50 characters
echo $test;
?>
test: UFOruSSTCPIqxTRIIMTRkqjOGidcVlhYaS9gtwttxglheVugFM
if you need two or more unique strings you can use this trick...
$string_1 = random_alphanumeric(50);
$string_2 = random_alphanumeric(50);
while ($string_1 == $string_2) {
$string_1 = random_alphanumeric(50);
$string_2 = random_alphanumeric(50);
if ($string_1 != $string_2) {
break;
}
}
echo $string_1;
echo "<br>\n";
echo $string_2;
$string_1: tMYicqLCHEvENwYbMUUVGTfkROxKIekEB2YXx5FHyVByp3mlJO
$string_2: XdMNJYpMlFRKFDlF6GhVn6jsBVNQ1BCCevj8yK2niFOgpDI2MU
I hope this help.
echo substr(bin2hex(random_bytes(14)), 0, $length);
this code gets a random bytes, that are converted from binary to hexadecimal, and then takes a substring of this hexadecimal string, as long you puts in $length variable
Try this
Simple enough!
function RandomFromCharset($charset,$length)
{
$characters = $charset; // your existing charset / defined string
$charactersLength = strlen($characters);
$random_from_charset = '';
for ($i = 0; $i < $length; $i++)
{
$random_from_charset.= $characters[rand(0, $charactersLength - 1)];
}
return random_from_charset;
}
Call the function as follows
RandomFromCharset($charset,$length);
where $length will be length of random string you want (this can be predefined also in the function as RandomFromCharset(charset,$length=10) ) to generate and $charset will be your existing string to which you want to restrict the characters.
One approach is to generate an md5 from a random number and extract the number of characters you want:
<?php
$random = substr(md5(mt_rand()), 0, 7);
echo $random;
?>
mt_rand will generate a random number, md5 will create a 32 character string (containing both letters and numbers) and, in this example, we're extracting the first 7 characters of text.
you could make an array of characters then use rand() to pick a letter from the array and added it to a string.
$letters = array( [0] => 'a' [1] => 'b' [2] => 'c' [3] => 'd' ... [25] = 'z');
$lengthOfString = 10;
$str = '';
while( $lengthOfString-- )
{
$str .= $letters[rand(0,25)];
}
echo $str;
*note that this does allow repeat characters
This builds on Gumbo's solution by adding functionality to list a set of characters to be skipped in the base character set. The random string selects characters from $base_charset which do not also appear in $skip_charset.
/* Make a random string of length using characters from $charset, excluding $skip_chars.
* #param length (integer) length of return value
* #param skip_chars (string) characters to be excluded from $charset
* #param charset (string) characters of posibilities for characters in return val
* #return (string) random string of length $length */
function rand_string(
$length,
$skip_charset = '',
$base_charset='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'){
$skip_len = strlen($skip_charset);
for ($i = 0; $i<$skip_len; $i++){
$base_charset = str_replace($skip_charset[$i], '', $base_charset);
}
cvar_dump($base_charset, '$base_charset after replace');
$str = '';
$count = strlen($base_charset);
while ($length--) {
$str .= $base_charset[mt_rand(0, $count - 1)];
}
return $str;
}
Here are some usage examples. The first two examples use the default value for $base_charset. The last example explicitly defines $base_charset.
echo rand_string(15, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz');
// 470620078953298
echo rand_string(8, 'abcdefghijklmnopqrstuvwxyz0123456789');
// UKLIHOTFSUZMFPU
echo rand_string(15, 'def', 'abcdef');
// cbcbbccbabccaba
well, I was looking for a solution, and I kindda used #Chad Birch's solution merged with #Gumbo's one. This is what I came up with:
function get_random_string($length, $valid_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456790!·$%&/()=?¿¡',.-;:+*`+´ç")
{
$random_string = "";
$num_valid_chars = strlen($valid_chars);
for ($i = 0; $i < $length; $i++, $random_string .= $valid_chars[mt_rand(1, $num_valid_chars)-1]);
return $random_string;
}
I think comments are pretty much unnecesary since the answers I used to build up this one are already thoroughly commented. Cheers!
If you're not concerned about time, memory, or cpu efficiency, and if your system can handle it, why not give this algorithm a try?!
function randStr($len, $charset = 'abcdABCD0123') {
$out = '';
$str = array();
for ($i = 0; $i < PHP_INT_MAX; $i++) {
$str[$i] = $charset;
shuffle($str);
$charset .= implode($charset, $str);
$charset = str_shuffle($charset);
}
$str = array_flip($str);
$str = array_keys($str);
for ($i = 0; $i < PHP_INT_MAX; $i++) {
shuffle($str);
}
$str = implode('', $str);
for ($i = 0; $i < strlen($str); $i++) {
$index = mt_rand(1, strlen($str));
$out .= $str[$index - 1];
}
for ($i = 0; $i < PHP_INT_MAX; $i++) {
$out = str_shuffle($out);
}
return substr($out, 0, $len);
}
Maybe this will read better if it uses recursion, but I'm not sure if PHP uses tail recursion or not...