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("The randomly generated string using hashing function sha1 is :");
echo $res;
?>

輸出

The randomly generated string using hashing function sha1 is :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 雜湊函式。生成的隨機字串將列印到控制檯。

更新日期:02-07-2020

264 次檢視

啟動您的事業

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.