Generate secure random strings in PHP

September 17, 2017 By - Usama Muneer | 640


    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.

    blog user
    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.

    Related Posts

    While Developing applications in Laravel, there comes situations where you have date in simple string format. For instance getting raw response from an API. But you want to convert that string into Carbon instance and use the Carbon helpers on it. Well there's a simple solution to it.

    If you have encountered an error not defined while uploading images for your WordPress custom posts or taxonomies.

    Laravel ships in with the awesomeness of Database Migrations which allows you to version control your database. But there are number of events when you are required to change the datatypes or attributes assigned to your table columns inside of your migrations.

    Sometimes you need to provide dropdowns in your exported excel files for more enhanced look on the data. Here's how we can achieve it.