{"id":100,"date":"2019-09-16T16:22:56","date_gmt":"2019-09-16T16:22:56","guid":{"rendered":"https:\/\/tutorialio.com\/?p=100"},"modified":"2025-11-04T10:31:59","modified_gmt":"2025-11-04T10:31:59","slug":"generate-a-random-alphanumeric-string-in-php","status":"publish","type":"post","link":"https:\/\/hellonitish.com\/blog\/generate-a-random-alphanumeric-string-in-php\/","title":{"rendered":"How Can I Generate a Random Alphanumeric String in PHP?"},"content":{"rendered":"<p>The need to generate a unique random alphanumeric string of a given length is very common. You may need it for various purpose like creating a random username or a filename. In this article, you will learn about different methods that can be used to generate random alphanumeric string in PHP.<\/p>\n<h2 id=\"using-strshuffle-to-generate-a-random-string\">Using str_shuffle() to Generate a Random String<\/h2>\n<p>In this section, we will be using different string functions to create our own random alphanumeric string generator function. Here is the first version of our function that generates a random alphanumeric string.<\/p>\n<p class=\"lang-name\">PHP<\/p>\n<pre><code class=\"language-php\">function random_alphanumeric_string($length) {\n    $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n    return substr(str_shuffle($chars), 0, $length);\n}\n\n\/\/ Output \u2014 FtUqw9QpC1\necho  random_alphanumeric_string(10);\n\n\/\/ Output \u2014 ZIPNz1kKvJ\necho  random_alphanumeric_string(10);\n<\/code><\/pre>\n<p>We begin by creating a <code>$chars<\/code> variable that stores all the characters we will be using to create our random string generator. You could also add other characters like <code>#, $, &amp;, @<\/code> to the mix.  After that, we have used the <a href=\"..\/string\/str-shuffle-function.php\">str_shuffle() function in PHP<\/a> to randomly shuffle the alphanumeric string value stored in <code>$chars<\/code>.  Finally, we return the first <code>$length<\/code> characters of the shuffled string using the <a href=\"..\/string\/substr-function.php\">substr() function in PHP<\/a>.<\/p>\n<p>For simple cases, this solution should be sufficient. However, there are two issues with it in its current form. First, the maximum length of string can only be 62 (10[0-9] + 26[a-z] + 26[A-Z] = 62) characters. Second, the characters inside the generated string will never repeat. We can solve both these issues with the help of <a href=\"..\/string\/str-repeat-function.php\">str_repeat() function in PHP<\/a> which repeats a string given number of times. Here is the second iteration of our function:<\/p>\n<p class=\"lang-name\">PHP<\/p>\n<pre><code class=\"language-php\">function random_alphanumeric_string($length) {\n    $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n    return substr(str_shuffle(str_repeat($chars, ceil($length\/strlen($chars)) )), 0, $length);\n}\n\n\/\/  Output \u2014 Z4VIz4gvnb0NQ6KHUej1lpCiYVbFdArA2Hw9RdkPyeftFGnaiwDEsPm7JjuLWSxMBDhZ72KT56xIkhqQtrmgGozaM0uf9cX83U15\necho  random_alphanumeric_string(100);\n<\/code><\/pre>\n<p>We divide the length of required random string with the length of the seed string, take its ceiling value and then repeat the seed string calculated number of times. For example, length of <code>$chars<\/code> is 62. If the supplied <code>$length<\/code> value is 100, <code>ceil(100\/62)<\/code> becomes 2. This means that our seed string will be repeated twice making its total length 124. The <code>substr()<\/code> function can then take the first 100 characters after the string has been shuffled.<\/p>\n<p>Now, the characters inside our random string will start repeating once its length becomes more than 62. However, this means that any random alphanumeric character sequence generated by our function with less than or equal to 62 characters will still have unique characters. We can slightly modify our function and specify the number of times the characters may be repeated along with the length of generated string.<\/p>\n<p class=\"lang-name\">PHP<\/p>\n<pre><code class=\"language-php\">function random_alphanumeric_string($length, $repeats) {\n    $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n    return substr(str_shuffle(str_repeat($chars, $repeats)), 0, $length);\n}\n\n\/\/  Output \u2014 AJ9H8NBKK4\necho  random_alphanumeric_string(10, 3);\n\n\/\/  Output \u2014 Wd8YtZcwqT\necho  random_alphanumeric_string(10, 3);\n<\/code><\/pre>\n<p>Now, the characters will repeat even if the string length is less than 62. This makes the generated string less predictable. However, you still should not use it cryptographic purposes like generating passwords. This is because <code>str_shuffle()<\/code> uses <code>rand()<\/code> to shuffle the string and <code>rand()<\/code> is the secure cryptography wise.<\/p>\n<h2 id=\"using-md5-and-sha1-to-generate-a-random-string\">Using md5() and sha1() to Generate a Random String<\/h2>\n<p>The <a href=\"..\/string\/md5-function.php\">md5() function available in PHP<\/a> can be used to calculate the md5 hash of a given string. For our purposes, we can supply it a random integer using <code>mt_rand()<\/code> or the current timestamp value using <code>time()<\/code>. The hash of the given input is returned as a 32 character hexadecimal number. This means that the maximum length of the returned hash will be 32 characters. We can use the <a href=\"..\/string\/substr-function.php\">substr() function<\/a> to extract a part of the output as our random string. Here is an example:<\/p>\n<p class=\"lang-name\">PHP<\/p>\n<pre><code class=\"language-php\">function random_md5_string($length) {\n    return substr(md5(time()), 0, $length);\n}\n\n\/\/  Output \u2014 e4c0c18a8dba\necho random_md5_string(12);\n\n\/\/  Output \u2014 b2ac061a4b0aab170474f28a\necho random_md5_string(24);\n<\/code><\/pre>\n<p>Similarly, you can also use the <code>sha1()<\/code> function to calculate the sha1 hash of a given string. Just like the previous example, we can supply it with an input value using <code>time()<\/code> or <code>mt_rand()<\/code>. The maximum length of returned hexadecimal string in this case would be 40 characters.<\/p>\n<p class=\"lang-name\">PHP<\/p>\n<pre><code class=\"language-php\">function random_sha1_string($length) {\n    return substr(sha1(mt_rand()), 0, $length);\n}\n\n\/\/  Output \u2014 52550a827ba2458e7128e2f5a7ccd34d3a7b\necho random_sha1_string(36);\n<\/code><\/pre>\n<h2 id=\"using-the-randombytes-function\">Using the random_bytes() Function<\/h2>\n<p>The methods we have used so far for generating our string are not meant to be used in cryptography based work. In such cases, you can use the <a href=\"http:\/\/php.net\/manual\/en\/function.random-bytes.php\">random_bytes() function in PHP<\/a> to generate cryptographically secure random bytes. This function is relatively new and only available in PHP 7. Here is an example of a random string generated using the <code>bin2hex()<\/code> and <code>random_bytes()<\/code> functions.<\/p>\n<p class=\"lang-name\">PHP<\/p>\n<pre><code class=\"language-php\">function random_string($length) {\n    echo substr(bin2hex(random_bytes($length)), 0, $length);\n}\n\n\/\/  Output \u2014 c92b5d7247241d7a8a63\necho random_string(20);\n<\/code><\/pre>\n<p>The <code>random_bytes()<\/code> function returns <code>$length<\/code> number of pseudo-random bytes. We are using the <a href=\"..\/string\/bin2hex-function.php\">bin2hex() function in PHP<\/a> to convert the returned binary string into a hexadecimal value. Finally, we extract the first <code>$length<\/code> characters from the hexadecimal string using <code>substr()<\/code> function.<\/p>\n<p>One major advantage of using <code>random_bytes()<\/code> is that it is cryptographically secure. However, it is only available in PHP 7.<\/p>\n<h2 id=\"quick-summary\">Quick Summary<\/h2>\n<p>Let\u2019s recap everything that we have covered in this tutorial.<\/p>\n<ol id=\"summary-points\">\n<li>You can use <code>str_shuffle()<\/code> to shuffle all the characters in an alphanumeric string. This alphanumeric string will consist of all the characters that you want to appear in your random string. After shuffling it, all the characters will be in random order and you can pick a substring of given length out of the shuffled string to get  your random alphanumeric string.<\/li>\n<li>If you only need a random hexadecimal string, you can use the <code>md5()<\/code> function to get a 32 characters long string. Similarly, you can use the <code>sha1()<\/code> function to get random hexadecimal strings with 40 characters.<\/li>\n<li>If you want to generate cryptographically secure random strings, you should consider using the <code>random_bytes()<\/code> function in PHP. You can then use the <code>hex2bin()<\/code> function to convert those random bytes into hexadecimal strings. However, the <code>random_bytes()<\/code> function is only available in PHP 7.<\/li>\n<\/ol>\n<p>Let me know if there is anything that you would like me to clarify in this tutorial. Also, you are more than welcome to comment if you know other techniques to generate a random alphanumeric string in PHP.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The need to generate a unique random alphanumeric string of a given length is very common. You may need it for various purpose like creating a random username or a filename. In this article, you will learn about different methods that can be used to generate random alphanumeric string in PHP. Using str_shuffle() to Generate [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[25],"tags":[],"class_list":["post-100","post","type-post","status-publish","format-standard","hentry","category-how-to-guides"],"_links":{"self":[{"href":"https:\/\/hellonitish.com\/blog\/wp-json\/wp\/v2\/posts\/100","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hellonitish.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hellonitish.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hellonitish.com\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hellonitish.com\/blog\/wp-json\/wp\/v2\/comments?post=100"}],"version-history":[{"count":1,"href":"https:\/\/hellonitish.com\/blog\/wp-json\/wp\/v2\/posts\/100\/revisions"}],"predecessor-version":[{"id":10247,"href":"https:\/\/hellonitish.com\/blog\/wp-json\/wp\/v2\/posts\/100\/revisions\/10247"}],"wp:attachment":[{"href":"https:\/\/hellonitish.com\/blog\/wp-json\/wp\/v2\/media?parent=100"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hellonitish.com\/blog\/wp-json\/wp\/v2\/categories?post=100"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hellonitish.com\/blog\/wp-json\/wp\/v2\/tags?post=100"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}