PHP程序生成随机字符串的不同方法
使用bin2hex函数
示例
<?php
$num = 12;
$res = bin2hex(random_bytes($num));
print_r("The randomly generated string is : ");
echo $res;
?>输出结果
The randomly generated string is : f1db16115fa93b98493d388b
定义一个数字,并在该数字上调用bin2hex函数。在bin2hex函数内部,此数字被调用'random_bytes'函数。生成的随机字符串将打印在控制台上。
使用哈希函数
示例
<?php
$my_str = rand();
$res = sha1($my_str);
print_r("使用哈希函数sha1随机生成的字符串是:");
echo $res;
?>输出结果
使用哈希函数sha1随机生成的字符串是:9a4a73c35ac034832332977f3d5accd8eace5260
通过调用“rand”函数定义一个数字。在此随机生成的数字上调用sha1哈希函数。生成的随机字符串将打印在控制台上。
使用内置函数uniqid
示例
<?php
$res = uniqid();
print_r("The randomly generated string using uniqid function is : ");
echo $res;
?>输出结果
The randomly generated string using uniqid function is : 5ed4b884cef34
通过调用“rand”函数定义一个数字。在此随机生成的数字上调用sha1哈希函数。生成的随机字符串将打印在控制台上。