Generating (pseudo)random alpha-numeric strings
Asked Answered
B

18

87

How can I generate a (pseudo)random alpha-numeric string, something like: 'd79jd8c' in PHP?

Boyla answered 7/9, 2008 at 4:2 Comment(2)
The Solution is short and unique. Refer this Link https://mcmap.net/q/48892/-one-line-php-random-string-generatorMelosa
The method Random::alphanumericString($length) does what you want. If you want to build this yourself, don’t use any random source other than PHP’s built-in random_bytes or random_int.Chiefly
F
166

First make a string with all your possible characters:

 $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';

You could also use range() to do this more quickly.

Then, in a loop, choose a random number and use it as the index to the $characters string to get a random character, and append it to your string:

 $string = '';
 $max = strlen($characters) - 1;
 for ($i = 0; $i < $random_string_length; $i++) {
      $string .= $characters[mt_rand(0, $max)];
 }

$random_string_length is the length of the random string.

Futuristic answered 7/9, 2008 at 4:6 Comment(8)
This implementation is also nice if you wish to remove characters that look the same such as "l" and "1", "O" and "0". This is worthwhile when generating new passwords for users.Harpole
I also use this technique and remove all the vowels so I don't accidentally give someone something rude for a password.Catechetical
You're missing a close parenthesis after the "- 1" and before the "]"Pulverable
Minor improvement: mt_rand() is a drop-in replacement for rand(), and is better.Metaphysic
Executing strlen() each iteration isn't good. Assign strlen($characters) - 1 to a variable and perform strlen out of the cycle. Not critical in this case, but it's just Mauvais ton.Ender
range definitely wouldn't do this more quickly. Nothing is quicker than a hard-coded string of 36 characters.Tortfeasor
Consider using random_int if you need a cryptographically secure random.Lithology
what is the propability of getting a duplicate string with this code?Strepphon
H
18

I like this function for the job

function randomKey($length) {
    $pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z'));

    for($i=0; $i < $length; $i++) {
        $key .= $pool[mt_rand(0, count($pool) - 1)];
    }
    return $key;
}

echo randomKey(20);
Hallucination answered 28/11, 2015 at 13:37 Comment(0)
E
14

Generate cryptographically strong, random (potentially) 8-character string using the openssl_random_pseudo_bytes function:

echo bin2hex(openssl_random_pseudo_bytes(4));

Procedural way:

function randomString(int $length): string
{
    return bin2hex(openssl_random_pseudo_bytes($length));
}

Update:

PHP7 introduced the random_x() functions which should be even better. If you come from PHP 5.X, use excellent paragonie/random_compat library which is a polyfill for random_bytes() and random_int() from PHP 7.

function randomString($length)
{
    return bin2hex(random_bytes($length));
}
Equivalence answered 24/2, 2016 at 14:41 Comment(0)
H
9

One line solution:

echo substr( str_shuffle( str_repeat( 'abcdefghijklmnopqrstuvwxyz0123456789', 10 ) ), 0, 7 );

You can change the substr parameter in order to set a different length for your string.

Hobnob answered 8/8, 2017 at 19:55 Comment(0)
S
4

Use the ASCII table to pick a range of letters, where the: $range_start , $range_end is a value from the decimal column in the ASCII table.

I find that this method is nicer compared to the method described where the range of characters is specifically defined within another string.

// range is numbers (48) through capital and lower case letters (122)
$range_start = 48;
$range_end   = 122;
$random_string = "";
$random_string_length = 10;

for ($i = 0; $i < $random_string_length; $i++) {
  $ascii_no = round( mt_rand( $range_start , $range_end ) ); // generates a number within the range
  // finds the character represented by $ascii_no and adds it to the random string
  // study **chr** function for a better understanding
  $random_string .= chr( $ascii_no );
}

echo $random_string;

See More:

Stiegler answered 7/9, 2008 at 10:4 Comment(1)
This is nice although non-alphanumeric characters fall within that ACSII range.Granth
M
4

I know it's an old post but I'd like to contribute with a class I've created based on Jeremy Ruten's answer and improved with suggestions in comments:

    class RandomString
    {
      private static $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
      private static $string;
      private static $length = 8; //default random string length

      public static function generate($length = null)
      {

        if($length){
          self::$length = $length;
        }

        $characters_length = strlen(self::$characters) - 1;

        for ($i = 0; $i < self::$length; $i++) {
          self::$string .= self::$characters[mt_rand(0, $characters_length)];
        }

        return self::$string;

      }

    }
Minor answered 13/11, 2015 at 10:38 Comment(0)
M
4

Simple guys .... but remember each byte is random between 0 and 255 which for a random string will be fine. Also remember you'll have two characters to represent each byte.

$str = bin2hex(random_bytes(32));  // 64 character string returned
Mackenie answered 2/5, 2019 at 14:59 Comment(1)
By far the best answer and the shortest code! This should get more upvotesCounterscarp
Q
2

You can use the following code. It is similar to existing functions except that you can force special character count:

function random_string() {
    // 8 characters: 7 lower-case alphabets and 1 digit
    $character_sets = [
        ["count" => 7, "characters" => "abcdefghijklmnopqrstuvwxyz"],
        ["count" => 1, "characters" => "0123456789"]
    ];
    $temp_array = array();
    foreach ($character_sets as $character_set) {
        for ($i = 0; $i < $character_set["count"]; $i++) {
            $random = random_int(0, strlen($character_set["characters"]) - 1);
            $temp_array[] = $character_set["characters"][$random];
        }
    }
    shuffle($temp_array);
    return implode("", $temp_array);
}
Querida answered 24/6, 2009 at 8:42 Comment(0)
L
2

Maybe I missed something here, but here's a way using the uniqid() function.

Liking answered 26/6, 2010 at 23:40 Comment(1)
uniqid is not random in any way. It's completely predictable. This question is very specifically looking for pseudorandom strings.Tortfeasor
C
2

I have made the following quick function just to play around with the range() function. It just might help someone sometime.

Function pseudostring($length = 50) {

    // Generate arrays with characters and numbers
    $lowerAlpha = range('a', 'z');
    $upperAlpha = range('A', 'Z');
    $numeric = range('0', '9');

    // Merge the arrays
    $workArray = array_merge($numeric, array_merge($lowerAlpha, $upperAlpha));
    $returnString = "";

    // Add random characters from the created array to a string
    for ($i = 0; $i < $length; $i++) {
        $character = $workArray[rand(0, 61)];
        $returnString .= $character;
    }

    return $returnString;
}
Carney answered 29/4, 2016 at 7:52 Comment(0)
T
1
function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
echo generateRandomString();
Trichromatism answered 8/3, 2015 at 10:48 Comment(0)
E
1

If you want a very easy way to do this, you can lean on existing PHP functions. This is the code I use:

substr( sha1( time() ), 0, 15 )

time() gives you the current time in seconds since epoch, sha1() encrypts it to a string of 0-9a-f, and substr() lets you choose a length. You don't have to start at character 0, and whatever the difference is between the two numbers will be the length of the string.

Exclamatory answered 16/4, 2018 at 14:51 Comment(0)
E
1

First list the desired characters

$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

Use the str_shuffle($string) function. This function will provide you a randomly shuffled string.

$alpha=substr(str_shuffle($chars), 0, 50);

50 is the Length of string.

Ethno answered 11/5, 2019 at 11:42 Comment(0)
M
0

Jeremy's answer is great. If, like me, you're unsure of how to implement range(), you can see my version using range().

<?php
$character_array = array_merge(range('a', 'z'), range(0, 9));
$string = "";
    for($i = 0; $i < 6; $i++) {
        $string .= $character_array[rand(0, (count($character_array) - 1))];
    }
echo $string;
?>

This does the exact same thing as Jeremy's but uses merged arrays where he uses a string, and uses count() where he uses strlen().

Mccarty answered 22/6, 2010 at 18:37 Comment(1)
it needs to be range('a','z');Morganne
G
0

This is something I use:

$cryptoStrong = true; // can be false
$length = 16; // Any length you want
$bytes = openssl_random_pseudo_bytes($length, $cryptoStrong);
$randomString = bin2hex($bytes);

You can see the Docs for openssl_random_pseudo_bytes here, and the Docs for bin2hex here

Granulocyte answered 28/12, 2016 at 11:44 Comment(0)
C
0

1 line:

$FROM = 0; $TO = 'zzzz';
$code = base_convert(rand( $FROM ,base_convert( $TO , 36,10)),10,36);
echo $code;
Culch answered 11/5, 2017 at 15:19 Comment(0)
T
0

The modern way to do that with type hint / rand_int for real randomeness

function random_string(int $size): string
{
    $characters = array_merge(
        range(0, 9),
        range('A', 'Z')
    );

    $string = '';
    $max = count($characters) - 1;
    for ($i = 0; $i < $size; $i++) {
        $string .= $characters[random_int(0, $max)];
    }

    return $string;
}
Thick answered 5/11, 2018 at 15:15 Comment(0)
M
0
public function randomString($length = 8)
{
    $characters = implode([
        'ABCDEFGHIJKLMNOPORRQSTUWVXYZ',
        'abcdefghijklmnoprqstuwvxyz',
        '0123456789',
        //'!@#$%^&*?'
    ]);

    $charactersLength = strlen($characters) - 1;
    $string           = '';

    while ($length) {
        $string .= $characters[mt_rand(0, $charactersLength)];
        --$length;
    }

    return $string;
}
Mint answered 11/5, 2019 at 11:48 Comment(1)
You have different number of characters in lower and upper case strings. And does this code have any advantages over all other variants already published here?Legg

© 2022 - 2024 — McMap. All rights reserved.