Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> PHP

Tạo chuỗi ngẫu nhiên bằng PHP

Để tạo chuỗi ngẫu nhiên bằng PHP, mã như sau:

Ví dụ

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

Kết quả

Điều này sẽ tạo ra kết quả sau:

Displaying random string... 1c856

Ví dụ

Hãy xem một ví dụ khác:

<?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; 
?>

Kết quả

Điều này sẽ tạo ra kết quả sau:

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