Introduction
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"
"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.
var_dump($crypto);
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.