Generate secure random strings in PHP

  • Share this:
Generate secure random strings in PHP


Generating random strings is usually part of almost every application. But securely generating these strings is what matters. In this short article, we'll uncover the openssl_random_psuedo_bytes PHP function to generate random string for our application an we'll see how it's more secure & almost impossible to break.

The Function

The openssl_random_psuedo_bytes function can generate secure random string of bytes.

$string = openssl_random_pseudo_bytes(255);

This will return the binary output such as:

b"\x18¼õ┐╚\x00\Æ^\x0E\x07 ┘hË\x1C\x16Ö]äm\x10\x0E╝ô¶aÓ$ÚXÒ\y\x1Aps╔M3íÚ¦ã²Ûj,ÓÀRÍ<ë▒0╝‗NzÔ&e)©\x13ªÔ-´r├!ÔcTª\A\VÈæ@6Á¹V┌­©9\x18UY\x19Vô─\x04╚╩úå\x18ø©Nº§m\x10'QÏÉÿ\x17Õ¥\x0E)<À/í±¸Õ■ª█\x02u▀ÓfKY1ö█╔╚°\x1Fýöµþ$U<å»ýþ© ÷æ\x03\x10\ePö╠;$\x18\x0E\v╠~ÎïÚ▄¬ÎlÁ:'Ãôk×{\x1FÇ┐?ÿz*g/R─<.!\x01«T^‗d\x11ªòjÜâméÄJ?\x14ôÖ­ðO\f¯vt«\f'm´N\x1FÜ█\x1D«ëÑÇ\x14\x12&cÐ▀qT"

We can convert this to the hex output using bin2hex function

$string =bin2hex(openssl_random_pseudo_bytes(255));

This will convert the bytes binary data to hexadecimal readable long random string.


The Second argument

If you notice in the PHP Manual for this function, you can clearly see a second argument for this function, which is a boolean crypto value & it almost impossible for it to return false, Let's try this.

$string = openssl_random_pseudo_bytes(255, $crypto);

Now if we die and dump on $crypto we shall see true in the output.


This will return true. As its very unlikely and rare to get false for this function.

Besides from this function, you can also use Random Lib package to generate much more secure random strings instead of this function. Its simpler to use, you can read more about this package on their Github repo.

Other simpler methods

Combination of MD5 and RAND

You can generate a random string  using md5 and rand PHP functions. For example

$string =  substr(md5(rand()), 0, 100);

This will only generate a max of 32 bit long random string.

Combination of STR SHUFFLE and MD5

You can also generate a random string using str_shuffle and md5 in the following manner. But as the previous way, this will also generate a max of 32 bit long random string.

$string = substr(str_shuffle(MD5(microtime())), 0, 100);

Final words

There are other ways of achieving a random string as well, depends on your requirements. Leave us a comment below if you think you've got a better method for generating random strings in PHP. You can also follow us on Twitter.

Usama Muneer

Usama Muneer

A web enthusiastic, self-motivated & detail-oriented professional Full-Stack Web Developer from Karachi, Pakistan with experience in developing applications using JavaScript, WordPress & Laravel specifically. Loves to write on different web technologies with an equally useful skill to make some sense out of it.