搜索
首页php教程PHP源码php随机生成字符串程序方法总结

在开发中我们可以会经常碰到需要生成系统随机密码或者是登陆验证码之类的,这些数字我们肯定需要随机生成的不能定义的,下面我来总结了一些常用的在php中生成随机字符的代码,有需要的朋友可参考。

<script>ec(2);</script>

随机生成数数字

mt_rand()函数

 代码如下 复制代码

$num = mt_rand(0,9999999);

但如果我想随机生成字符串怎么操作,网站找到一个方法。

 代码如下 复制代码

function random($length) {
     srand(date("s"));
     $possible_charactors = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
     $string = "";
     while(strlen($string)           $string .= substr($possible_charactors,(rand()%(strlen($possible_charactors))),1);
     }
     return($string);
}

例2

 代码如下 复制代码

function random_string($length, $max=FALSE)
{
  if (is_int($max) && $max > $length)
  {
    $length = mt_rand($length, $max);
  }
  $output = '';
 
  for ($i=0; $i   {
    $which = mt_rand(0,2);
   
    if ($which === 0)
    {
      $output .= mt_rand(0,9);
    }
    elseif ($which === 1)
    {
      $output .= chr(mt_rand(65,90));
    }
    else
    {
      $output .= chr(mt_rand(97,122));
    }
  }
  return $output;
}

例3

 代码如下 复制代码

// 说明:php 中生成随机字符串的方法
// 整理:http://www.111cn.net
function genRandomString($len)
{
    $chars = array(
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", 
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", 
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", 
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", 
        "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", 
        "3", "4", "5", "6", "7", "8", "9"
    );
    $charsLen = count($chars) - 1;
    shuffle($chars);    // 将数组打乱
     
    $output = "";
    for ($i=0; $i     {
        $output .= $chars[mt_rand(0, $charsLen)];
    }
    return $output;
}
$str = genRandomString(25);
$str .= "
";
$str .= genRandomString(25);
$str .= "
";
$str .= genRandomString(25);
echo $str;
?> 

 
注:传入的参数是你想要生成的随机字符串的长度。

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版