Computer >> Computer tutorials >  >> Programming >> PHP

Generating Random String Using PHP


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

Example

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

Output

This will produce the following output−

Displaying random string...
1c856

Example

Let us now see another example −

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

Output

This will produce the following output−

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