How to Generate a Random Key Within PHP

What is the best way to generate a random key within PHP?

Update (12/2015): For PHP 7.0, you should use random_int() instead of mt_rand as it provides "cryptographically secure values"

Personally, I like to use sha1(microtime(true).mt_rand(10000,90000)) but you are looking for more of a customizable approach, so try this function (which is a modification to your request of this answer):

function rand_char($length) {
$random = '';
for ($i = 0; $i < $length; $i++) {
$random .= chr(mt_rand(33, 126));
}
return $random;
}

Still, this will probably be significantly slower than uniqid(), md5(), or sha1().

Edit: Looks like you got to it first, sorry. :D

Edit 2: I decided to do a nice little test on my Debian machine with PHP 5 and eAccelerator (excuse the long code):

function rand_char($length) {
$random = '';
for ($i = 0; $i < $length; $i++) {
$random .= chr(mt_rand(33, 126));
}
return $random;
}

function rand_sha1($length) {
$max = ceil($length / 40);
$random = '';
for ($i = 0; $i < $max; $i ++) {
$random .= sha1(microtime(true).mt_rand(10000,90000));
}
return substr($random, 0, $length);
}

function rand_md5($length) {
$max = ceil($length / 32);
$random = '';
for ($i = 0; $i < $max; $i ++) {
$random .= md5(microtime(true).mt_rand(10000,90000));
}
return substr($random, 0, $length);
}

$a = microtime(true);
for ($x = 0; $x < 1000; $x++)
$temp = rand_char(1000);

echo "Rand:\t".(microtime(true) - $a)."\n";

$a = microtime(true);
for ($x = 0; $x < 1000; $x++)
$temp = rand_sha1(1000);

echo "SHA-1:\t".(microtime(true) - $a)."\n";

$a = microtime(true);
for ($x = 0; $x < 1000; $x++)
$temp = rand_md5(1000);

echo "MD5:\t".(microtime(true) - $a)."\n";

Results:

Rand:   2.09621596336
SHA-1: 0.611464977264
MD5: 0.618473052979

So my suggestion, if you want speed (but not full charset), is to stick to MD5, SHA-1, or Uniqid (which I didn't test.. yet)

easiest way to generate an unique and random key

I prefer to generate a GUID. Here is some code that will do that for you.

 function getGUID(){
if (function_exists('com_create_guid')){
return com_create_guid();
}else{
mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
$charid = strtoupper(md5(uniqid(rand(), true)));
$hyphen = chr(45);// "-"
$uuid = chr(123)// "{"
.substr($charid, 0, 8).$hyphen
.substr($charid, 8, 4).$hyphen
.substr($charid,12, 4).$hyphen
.substr($charid,16, 4).$hyphen
.substr($charid,20,12)
.chr(125);// "}"
return $uuid;
}
}

$GUID = getGUID();
echo $GUID;

Here is my source. http://guid.us/GUID/PHP

PHP random string generator

To answer this question specifically, two problems:

  1. $randstring is not in scope when you echo it.
  2. The characters are not getting concatenated together in the loop.

Here's a code snippet with the corrections:

function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}

Output the random string with the call below:

// Echo the random string.
// Optionally, you can give it a desired string length.
echo generateRandomString();

Please note that this generates predictable random strings. If you want to create secure tokens, see this answer.

Pick a random key of an array but forcing one of the values

There is also this method using array_walk(DEMO):

$A = array();
$A['lemonade'] = array('a','b','g');
$A['tree'] = array('a','b','f');
$A['willpower'] = array('a','b','g');

$bro = $A;
array_walk($A, function($item, $key) use (&$bro)
{
if($item[2] != 'g')
{
unset($bro[$key]);
}
});

var_dump($bro);

How to create a random string using PHP?

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.

php associative array select 1 random value with key

You can use array_keys to get the keys in a indexed array.

The just use array_rand just like you did to pick one and echo the $arr associative key.

$keys = array_keys($arr);
$random = $keys[array_rand($keys,1)];
Echo $random . " => " . $arr[$random];

https://3v4l.org/miacb

How to get random value out of an array?

You can also do just:

$k = array_rand($array);
$v = $array[$k];

This is the way to do it when you have an associative array.



Related Topics



Leave a reply



Submit