Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

โปรแกรม PHP วิธีต่างๆ สร้าง Random String


ใช้ฟังก์ชัน 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 บนตัวเลขนี้ สตริงสุ่มที่สร้างขึ้นพิมพ์บนคอนโซล

ใช้ฟังก์ชัน hashing

ตัวอย่าง

<?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 เรียกฟังก์ชัน hash sha1 บนตัวเลขสุ่มนี้ สตริงสุ่มที่สร้างขึ้นพิมพ์บนคอนโซล

ใช้ฟังก์ชัน built-in 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 เรียกฟังก์ชัน hash sha1 บนตัวเลขสุ่มนี้ สตริงสุ่มที่สร้างขึ้นพิมพ์บนคอนโซล (หมายเหตุ: คำอธิบายซ้ำจากตัวอย่างก่อนหน้า)