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

[{'answer_id': 48125, 'author': 'Paige Ruten', 'author_id': 813, 'author_profile': 'https://Stackoverflow.com/users/813', 'pm_score': 8, 'selected': True, 'text': '<p>First make a string with all your possible characters:</p>\n\n<pre><code> $characters = \'abcdefghijklmnopqrstuvwxyz0123456789\';\n</code></pre>\n\n<p>You could also use <a href="http://php.net/range" rel="noreferrer">range()</a> to do this more quickly.</p>\n\n<p>Then, in a loop, choose a random number and use it as the index to the <code>$characters</code> string to get a random character, and append it to your string:</p>\n\n<pre><code> $string = \'\';\n $max = strlen($characters) - 1;\n for ($i = 0; $i &lt; $random_string_length; $i++) {\n      $string .= $characters[mt_rand(0, $max)];\n }\n</code></pre>\n\n<p><code>$random_string_length</code> is the length of the random string.</p>\n'}, {'answer_id': 48285, 'author': 'Daniel', 'author_id': 416, 'author_profile': 'https://Stackoverflow.com/users/416', 'pm_score': 2, 'selected': False, 'text': '<p>Use the <a href="http://www.asciitable.com/" rel="nofollow noreferrer">ASCII table</a> to pick a range of letters, where the: $range_start , $range_end is a value from the decimal column in the ASCII table.</p>\n\n<p>I find that this method is nicer compared <a href="https://stackoverflow.com/questions/48124/generating-pseudorandom-alpha-numeric-strings#48125">to the method described</a> where the range of characters is specifically defined within another string.</p>\n\n<pre><code>// range is numbers (48) through capital and lower case letters (122)\n$range_start = 48;\n$range_end   = 122;\n$random_string = "";\n$random_string_length = 10;\n\nfor ($i = 0; $i &lt; $random_string_length; $i++) {\n  $ascii_no = round( mt_rand( $range_start , $range_end ) ); // generates a number within the range\n  // finds the character represented by $ascii_no and adds it to the random string\n  // study **chr** function for a better understanding\n  $random_string .= chr( $ascii_no );\n}\n\necho $random_string;\n</code></pre>\n\n<p>See More:</p>\n\n<ul>\n<li><a href="http://au.php.net/chr" rel="nofollow noreferrer">chr</a> function</li>\n<li><a href="http://au.php.net/mt_rand" rel="nofollow noreferrer">mt_rand</a> function</li>\n</ul>\n'}, {'answer_id': 1037136, 'author': 'Salman A', 'author_id': 87015, 'author_profile': 'https://Stackoverflow.com/users/87015', 'pm_score': 2, 'selected': False, 'text': '<p>You can use the following code. It is similar to existing functions except that you can force special character count:</p>\n<pre class="lang-php prettyprint-override"><code>function random_string() {\n    // 8 characters: 7 lower-case alphabets and 1 digit\n    $character_sets = [\n        [&quot;count&quot; =&gt; 7, &quot;characters&quot; =&gt; &quot;abcdefghijklmnopqrstuvwxyz&quot;],\n        [&quot;count&quot; =&gt; 1, &quot;characters&quot; =&gt; &quot;0123456789&quot;]\n    ];\n    $temp_array = array();\n    foreach ($character_sets as $character_set) {\n        for ($i = 0; $i &lt; $character_set[&quot;count&quot;]; $i++) {\n            $random = random_int(0, strlen($character_set[&quot;characters&quot;]) - 1);\n            $temp_array[] = $character_set[&quot;characters&quot;][$random];\n        }\n    }\n    shuffle($temp_array);\n    return implode(&quot;&quot;, $temp_array);\n}\n</code></pre>\n'}, {'answer_id': 3096086, 'author': 'Josh Smith', 'author_id': 373496, 'author_profile': 'https://Stackoverflow.com/users/373496', 'pm_score': 0, 'selected': False, 'text': '<p>Jeremy\'s answer is great. If, like me, you\'re unsure of how to implement range(), you can see my version using range().</p>\n\n<pre><code>&lt;?php\n$character_array = array_merge(range(\'a\', \'z\'), range(0, 9));\n$string = "";\n    for($i = 0; $i &lt; 6; $i++) {\n        $string .= $character_array[rand(0, (count($character_array) - 1))];\n    }\necho $string;\n?&gt;\n</code></pre>\n\n<p>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().</p>\n'}, {'answer_id': 3125854, 'author': 'Edward Fuller', 'author_id': 29801, 'author_profile': 'https://Stackoverflow.com/users/29801', 'pm_score': 2, 'selected': False, 'text': '<p>Maybe I missed something here, but <a href="http://php.net/manual/en/function.uniqid.php" rel="nofollow noreferrer">here\'s a way using the uniqid() function</a>.</p>\n'}, {'answer_id': 28925556, 'author': 'Molla Rasel', 'author_id': 4646424, 'author_profile': 'https://Stackoverflow.com/users/4646424', 'pm_score': 1, 'selected': False, 'text': "<pre><code>function generateRandomString($length = 10) {\n    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n    $charactersLength = strlen($characters);\n    $randomString = '';\n    for ($i = 0; $i &lt; $length; $i++) {\n        $randomString .= $characters[rand(0, $charactersLength - 1)];\n    }\n    return $randomString;\n}\necho generateRandomString();\n</code></pre>\n"}, {'answer_id': 33690821, 'author': 'diegoiglesias', 'author_id': 972813, 'author_profile': 'https://Stackoverflow.com/users/972813', 'pm_score': 2, 'selected': False, 'text': "<p>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:</p>\n\n<pre><code>    class RandomString\n    {\n      private static $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';\n      private static $string;\n      private static $length = 8; //default random string length\n\n      public static function generate($length = null)\n      {\n\n        if($length){\n          self::$length = $length;\n        }\n\n        $characters_length = strlen(self::$characters) - 1;\n\n        for ($i = 0; $i &lt; self::$length; $i++) {\n          self::$string .= self::$characters[mt_rand(0, $characters_length)];\n        }\n\n        return self::$string;\n\n      }\n\n    }\n</code></pre>\n"}, {'answer_id': 33971950, 'author': 'azerafati', 'author_id': 3160597, 'author_profile': 'https://Stackoverflow.com/users/3160597', 'pm_score': 4, 'selected': False, 'text': "<p>I like this function for the job</p>\n\n<pre><code>function randomKey($length) {\n    $pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z'));\n\n    for($i=0; $i &lt; $length; $i++) {\n        $key .= $pool[mt_rand(0, count($pool) - 1)];\n    }\n    return $key;\n}\n\necho randomKey(20);\n</code></pre>\n"}, {'answer_id': 35605166, 'author': 'emix', 'author_id': 997162, 'author_profile': 'https://Stackoverflow.com/users/997162', 'pm_score': 4, 'selected': False, 'text': '<p>Generate cryptographically strong, random (potentially) 8-character string using the <a href="http://php.net/openssl_random_pseudo_bytes" rel="noreferrer">openssl_random_pseudo_bytes</a> function:</p>\n\n<pre><code>echo bin2hex(openssl_random_pseudo_bytes(4));\n</code></pre>\n\n<p>Procedural way:</p>\n\n<pre><code>function randomString(int $length): string\n{\n    return bin2hex(openssl_random_pseudo_bytes($length));\n}\n</code></pre>\n\n<p><strong>Update:</strong></p>\n\n<p>PHP7 introduced the <code>random_x()</code> functions which should be even better. If you come from PHP 5.X, use excellent <a href="https://packagist.org/packages/paragonie/random_compat" rel="noreferrer">paragonie/random_compat</a> library which is a polyfill for <a href="http://php.net/random_bytes" rel="noreferrer">random_bytes()</a> and <a href="http://php.net/random_int" rel="noreferrer">random_int()</a> from PHP 7.</p>\n\n<pre><code>function randomString($length)\n{\n    return bin2hex(random_bytes($length));\n}\n</code></pre>\n'}, {'answer_id': 36932671, 'author': 'Peter', 'author_id': 3169577, 'author_profile': 'https://Stackoverflow.com/users/3169577', 'pm_score': 2, 'selected': False, 'text': '<p>I have made the following quick function just to play around with the <code>range()</code> function. It just might help someone sometime.</p>\n\n<pre><code>Function pseudostring($length = 50) {\n\n    // Generate arrays with characters and numbers\n    $lowerAlpha = range(\'a\', \'z\');\n    $upperAlpha = range(\'A\', \'Z\');\n    $numeric = range(\'0\', \'9\');\n\n    // Merge the arrays\n    $workArray = array_merge($numeric, array_merge($lowerAlpha, $upperAlpha));\n    $returnString = "";\n\n    // Add random characters from the created array to a string\n    for ($i = 0; $i &lt; $length; $i++) {\n        $character = $workArray[rand(0, 61)];\n        $returnString .= $character;\n    }\n\n    return $returnString;\n}\n</code></pre>\n'}, {'answer_id': 41361411, 'author': 'Zeeshan', 'author_id': 3354721, 'author_profile': 'https://Stackoverflow.com/users/3354721', 'pm_score': 0, 'selected': False, 'text': '<p>This is something I use:</p>\n\n<pre><code>$cryptoStrong = true; // can be false\n$length = 16; // Any length you want\n$bytes = openssl_random_pseudo_bytes($length, $cryptoStrong);\n$randomString = bin2hex($bytes);\n</code></pre>\n\n<p>You can see the <a href="http://php.net/manual/en/function.openssl-random-pseudo-bytes.php" rel="nofollow noreferrer">Docs for openssl_random_pseudo_bytes here</a>, and the <a href="http://php.net/manual/en/function.bin2hex.php" rel="nofollow noreferrer">Docs for bin2hex here</a></p>\n'}, {'answer_id': 43919537, 'author': 'HausO', 'author_id': 2842514, 'author_profile': 'https://Stackoverflow.com/users/2842514', 'pm_score': 0, 'selected': False, 'text': "<p>1 line:</p>\n\n<pre><code>$FROM = 0; $TO = 'zzzz';\n$code = base_convert(rand( $FROM ,base_convert( $TO , 36,10)),10,36);\necho $code;\n</code></pre>\n"}, {'answer_id': 45577038, 'author': 'Marco Panichi', 'author_id': 162049, 'author_profile': 'https://Stackoverflow.com/users/162049', 'pm_score': 3, 'selected': False, 'text': "<p>One line solution:</p>\n\n<pre><code>echo substr( str_shuffle( str_repeat( 'abcdefghijklmnopqrstuvwxyz0123456789', 10 ) ), 0, 7 );\n</code></pre>\n\n<p>You can change the substr parameter in order to set a different length for your string.</p>\n"}, {'answer_id': 49860249, 'author': 'DiMono', 'author_id': 2069424, 'author_profile': 'https://Stackoverflow.com/users/2069424', 'pm_score': 1, 'selected': False, 'text': "<p>If you want a very easy way to do this, you can lean on existing PHP functions. This is the code I use:</p>\n\n<p><code>substr( sha1( time() ), 0, 15 )</code></p>\n\n<p><code>time()</code> gives you the current time in seconds since epoch, <code>sha1()</code> encrypts it to a string of 0-9a-f, and <code>substr()</code> 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.</p>\n"}, {'answer_id': 53157130, 'author': 'lyrixx', 'author_id': 685587, 'author_profile': 'https://Stackoverflow.com/users/685587', 'pm_score': 0, 'selected': False, 'text': "<p>The modern way to do that with type hint / rand_int for real randomeness </p>\n\n<pre><code>function random_string(int $size): string\n{\n    $characters = array_merge(\n        range(0, 9),\n        range('A', 'Z')\n    );\n\n    $string = '';\n    $max = count($characters) - 1;\n    for ($i = 0; $i &lt; $size; $i++) {\n        $string .= $characters[random_int(0, $max)];\n    }\n\n    return $string;\n}\n</code></pre>\n"}, {'answer_id': 55955195, 'author': 'David Young', 'author_id': 11442440, 'author_profile': 'https://Stackoverflow.com/users/11442440', 'pm_score': 2, 'selected': False, 'text': "<p>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.</p>\n\n<pre><code>$str = bin2hex(random_bytes(32));  // 64 character string returned\n</code></pre>\n"}, {'answer_id': 56090016, 'author': 'Shravan M', 'author_id': 9512364, 'author_profile': 'https://Stackoverflow.com/users/9512364', 'pm_score': 1, 'selected': False, 'text': "<p>First list the desired characters</p>\n\n<pre><code>$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n</code></pre>\n\n<p>Use the str_shuffle($string) function. This function will provide you a randomly shuffled string.</p>\n\n<pre><code>$alpha=substr(str_shuffle($chars), 0, 50);\n</code></pre>\n\n<p>50 is the Length of string.</p>\n"}, {'answer_id': 56090053, 'author': 'Александр Маринов', 'author_id': 8847970, 'author_profile': 'https://Stackoverflow.com/users/8847970', 'pm_score': 0, 'selected': False, 'text': "<pre><code>public function randomString($length = 8)\n{\n    $characters = implode([\n        'ABCDEFGHIJKLMNOPORRQSTUWVXYZ',\n        'abcdefghijklmnoprqstuwvxyz',\n        '0123456789',\n        //'!@#$%^&amp;*?'\n    ]);\n\n    $charactersLength = strlen($characters) - 1;\n    $string           = '';\n\n    while ($length) {\n        $string .= $characters[mt_rand(0, $charactersLength)];\n        --$length;\n    }\n\n    return $string;\n}\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/48124', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/115/']