Generating Random String Using PHP



To generate random string using PHP, the code is as follows−

Example

 Live Demo

<?php
   $res = substr(md5(mt_rand()), 0,5);
   echo "Displaying random string...
";    echo $res; ?>

Output

This will produce the following output−

Displaying random string...
1c856

Example

Let us now see another example −

 Live Demo

<?php
   $res = substr(md5(mt_rand()), 0,5);
   echo "Displaying random string...
";    echo $res;    echo "
Displaying another random string...
";    $res2 = bin2hex(random_bytes(5));    echo $res2; ?>

Output

This will produce the following output−

Displaying random string...
a3541
Displaying another random string... 
335b83d9e9

Advertisements