Home php教程 php手册 php生成随机密码的方法总结

php生成随机密码的方法总结

Jun 21, 2016 am 08:49 AM
function length time

使用PHP开发应用程序,尤其是网站程序,常常需要生成随机密码,如用户注册生成随机密码,用户重置密码也需要生成一个随机的密码。随机密码也就是一串固定长度的字符串,这里我收集整理了几种生成随机字符串的方法,以供大家参考。

方法一:

1、在 33 – 126 中生成一个随机整数,如 35,
2、将 35 转换成对应的ASCII码字符,如 35 对应 #
3、重复以上 1、2 步骤 n 次,连接成 n 位的密码

该算法主要用到了两个函数,mt_rand ( int $min , int $max )函数用于生成随机整数,其中 $min – $max 为 ASCII 码的范围,这里取 33 -126 ,可以根据需要调整范围,如ASCII码表中 97 – 122 位对应 a – z 的英文字母,具体可参考 ASCII码表; chr ( int $ascii )函数用于将对应整数 $ascii 转换成对应的字符,具体的函数代码如下:

function create_password($pw_length=8){
    $randpwd='';
    for($i=0;$i
<p><font face="Courier New">使用方法如下,这里生成一个长度为6的随机密码:</font></p>
<pre title="code">
echo create_password(6);
Copy after login

方法二:

1、预置一个的字符串 $chars ,包括 a – z,A – Z,0 – 9,以及一些特殊字符
2、在 $chars 字符串中随机取一个字符
3、重复第二步 n 次,可得长度为 n 的密码

function generate_password($length=8){
    // 密码字符集,可任意添加你需要的字符
    $chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_ []{}~`+=,.;:/?';
    $password='';
    for($i=0;$i
<p><span style="color: #ff0000"><strong><font face="Courier New">方法三:</font></strong></span></p>
<p><font face="Courier New">1、预置一个的字符数组 $chars ,包括 a – z,A – Z,0 – 9,以及一些特殊字符<br>
2、通过array_rand()从数组 $chars 中随机选出 $length 个元素<br>
3、根据已获取的键名数组 $keys,从数组 $chars 取出字符拼接字符串。该方法的缺点是相同的字符不会重复取。</font></p>
<pre title="code">
function make_password($length=8){
    // 密码字符集,可任意添加你需要的字符
    $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','!',
    '@','#','$','%','^','&','*','(',')','-','_',
    '[',']','{','}','','~','`','+','=',',',
    '.',';',':','/','?','');
    // 在 $chars 中随机取 $length 个数组元素键名
    $keys=array_rand($chars,$length);
    $password='';
    for($i=0;$i
<p><span style="color: #ff0000"><strong><font face="Courier New">方法四:</font></strong></span></p>
<p><font face="Courier New">1、time() 获取当前的 Unix 时间戳<br>
2、将第一步获取的时间戳进行 md5() 加密<br>
3、将第二步加密的结果,截取 n 位即得想要的密码</font></p>
<pre title="code">
function get_password($length=8){
    $str=substr(md5(time()),0,6);
    return $str;
}
Copy after login

时间效率对比

我们使用以下PHP代码,计算上面的 4 个随机密码生成函数生成 6 位密码的运行时间,进而对他们的时间效率进行一个简单的对比。

<?php function getmicrotime(){
    list($usec,$sec)=explode(" ",microtime());
    return((float)$usec+(float)$sec);
}
// 记录开始时间
$time_start=getmicrotime();
// 这里放要执行的PHP代码,如:
// echo create_password(6);
// 记录结束时间
$time_end=getmicrotime();
$time=$time_end-$time_start;
 // 输出运行总时间 
echo "执行时间 $time seconds";
?>
Copy after login

对于以上测试程序运行时间的方法,也可参照本站文章:

PHP计算程序运行时间的类

最终得出的结果是:

方法一:9.8943710327148E-5 秒
方法二:9.6797943115234E-5 秒
方法三:0.00017499923706055 秒
方法四:3.4093856811523E-5 秒

综上可以看出方法一和方法二的执行时间都差不多,方法四运行时间最短,而方法三的运行时间稍微长点。



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What does function mean? What does function mean? Aug 04, 2023 am 10:33 AM

Function means function. It is a reusable code block with specific functions. It is one of the basic components of a program. It can accept input parameters, perform specific operations, and return results. Its purpose is to encapsulate a reusable block of code. code to improve code reusability and maintainability.

Monotonic clock processing of time package Monotonic clock processing of time package Aug 04, 2023 pm 05:45 PM

Today we are mainly going to take a look at the time application method of golang time package. The general rule between the two is that "wall time" is used to tell time, and "monotonic clock" is used to measure time; there are other clock processing methods.

Use java's String.length() function to get the length of a string Use java's String.length() function to get the length of a string Jul 25, 2023 am 09:09 AM

Use Java's String.length() function to get the length of a string. In Java programming, string is a very common data type. We often need to get the length of a string, that is, the number of characters in the string. In Java, we can use the length() function of the String class to get the length of a string. Here is a simple example code: publicclassStringLengthExample{publ

What is the purpose of the 'enumerate()' function in Python? What is the purpose of the 'enumerate()' function in Python? Sep 01, 2023 am 11:29 AM

In this article, we will learn about enumerate() function and the purpose of “enumerate()” function in Python. What is the enumerate() function? Python's enumerate() function accepts a data collection as a parameter and returns an enumeration object. Enumeration objects are returned as key-value pairs. The key is the index corresponding to each item, and the value is the items. Syntax enumerate(iterable,start) Parameters iterable - The passed in data collection can be returned as an enumeration object, called iterablestart - As the name suggests, the starting index of the enumeration object is defined by start. if we ignore

Detailed explanation of the role and function of the MySQL.proc table Detailed explanation of the role and function of the MySQL.proc table Mar 16, 2024 am 09:03 AM

Detailed explanation of the role and function of the MySQL.proc table. MySQL is a popular relational database management system. When developers use MySQL, they often involve the creation and management of stored procedures (StoredProcedure). The MySQL.proc table is a very important system table. It stores information related to all stored procedures in the database, including the name, definition, parameters, etc. of the stored procedures. In this article, we will explain in detail the role and functionality of the MySQL.proc table

How to use Java8 Time API How to use Java8 Time API Apr 28, 2023 pm 12:25 PM

1. Overview As part of this article, let us start with some problems with the existing Date and CalendarAPI and explore how the new Java8Date and TimeAPI solve these problems. We will also take a look at the core classes in the Java8 time class library, such as LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Period, Duration and their APIs. 2. The problem of thread safety of the old time API (before Java 8)-Date and Calendar classes are not thread-safe, making it difficult for developers to debug concurrency problems of these APIs and need to write additional code to deal with them.

What is the difference and usage between time and datetime in python What is the difference and usage between time and datetime in python May 02, 2023 am 11:01 AM

1. Two ways to represent time in Python: timestamp: offset in seconds relative to 1970.1.100:00:00, unique time tuple struct_time: a total of 9 elements>tm_year: year 1-12> tm_mon: month 1-12>tm_mday: day 1-31>tm_hour: hour 0-23>tm_min: minute 0-59>tm_sec: second 0-59>tm_wday: week 0-6 (0 means Sunday)>tm_day: Day of the year 1-366>tm_isdst: whether it is daylight saving, the default is -1.ti

The usage and function of Vue.use function The usage and function of Vue.use function Jul 24, 2023 pm 06:09 PM

Usage and Function of Vue.use Function Vue is a popular front-end framework that provides many useful features and functions. One of them is the Vue.use function, which allows us to use plugins in Vue applications. This article will introduce the usage and function of the Vue.use function and provide some code examples. The basic usage of the Vue.use function is very simple, just call it before Vue is instantiated, passing in the plugin you want to use as a parameter. Here is a simple example: //Introduce and use the plug-in

See all articles