PHP生成随机字符串的两个函数
作者:韩明剑
时间:2021-05-05
浏览:16
点赞:0

概述:本文为使用PHP生成随机字符串的2个函数示例。

示例1:

<?php   
function randStr($len=6) {   
$chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
mt_srand((double)microtime()*1000000*getmypid());
$randString='';   
while(strlen($randString)<$len)   
$randString.=substr($chars,(mt_rand()%strlen($chars)),1);   
return $randString;   
}  
echo randStr();
?>

示例2:

<?php
header("Content-type:text/html;charset=utf-8");
function randStr($length = 6){
 $randString = '';
 $chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
 $char_len = strlen($chars);
 for($i=0;$i<$length;$i++){
  $loop = mt_rand(0, ($char_len-1));
  $randString .= $chars[$loop];
 }
 return $randString;
}
echo randStr();
?>

原创不易,转载请保留本站版权。