如何使用PHP生成随机字符串

时间:2019-05-19 01:26:17  来源:igfitidea点击:

本教程将使用PHP生成随机字符串。随机字符串对于生成密码等很有用。

方法1–自定义函数

这是一个自定义函数,用于生成定义长度的随机字符串。使用此选项可以限制随机字符串中使用的字符和符号。

<?php

function generateRandomString($length) {
    $include_chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    /* 如果要包含符号,请把下面这行取消注释 */
    /* $include_chars .= "[{(!@#$%^/&*_+;?\:)}]"; */
    $charLength = strlen($include_chars);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $include_chars [rand(0, $charLength - 1)];
    }
    return $randomString;
}

// 调用函数
$lenght = 12; # Set result string lenght
echo generateRandomString($lenght);

?> 

输出:

a35ABfikMV

方法2–使用uniqid()函数

uniqid()函数的作用是:根据当前时间(微秒)生成一个唯一的id。此函数有一个限制,结果字符串的固定长度为13个字符。

<?php
  $result = uniqid();   
  echo $result; 
?>

输出:

135cdb68bf5cccf

方法3–使用random_bytes()函数

random_bytes()函数的作用是:生成一个加密安全的伪随机字节。此结果将采用二进制格式,我们可以使用bin2hex()函数将其转换为十六进制值。

<?php
  $bytes = 10;
  $result = bin2hex(random_bytes($bytes));
  echo $result;
?>

输出:

aa3613236ee7802b342867