PHP program different ways to generate a random string

Using bin2hex function

Example

Live Demo

<?php
$num = 12;$res = bin2hex(random_bytes($num)); print_r("The randomly generated string is : "); echo$res;
?>

Output

The randomly generated string is : f1db16115fa93b98493d388b

A number is defined and the bin2hex function is called on this number. Inside the bin2hex function the ‘random_bytes’ function is called on this number. The generated random string is printed on the console.

Using hashing function

Example

Live Demo

<?php
$my_str = rand();$res = sha1($my_str); print_r("The randomly generated string using hashing function sha1 is :"); echo$res;
?>

Output

The randomly generated string using hashing function sha1 is :9a4a73c35ac034832332977f3d5accd8eace5260

A number is defined by calling the ‘rand’ function. The sha1 hashing function is called on this randomly generated number. The generated random string is printed on the console.

Using built-in function uniqid

Example

Live Demo

<?php
$res = uniqid(); print_r("The randomly generated string using uniqid function is : "); echo$res;
?>

Output

The randomly generated string using uniqid function is : 5ed4b884cef34

A number is defined by calling the ‘rand’ function. The sha1 hashing function is called on this randomly generated number. The generated random string is printed on the console.