php 如何用PHP生成随机密码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1837432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:00:58  来源:igfitidea点击:

How to generate random password with PHP?

phprandompasswords

提问by user198729

Or is there a software to auto generate random passwords?

或者有没有自动生成随机密码的软件?

回答by Matt Huggins

Just build a string of random a-z, A-Z, 0-9(or whatever you want) up to the desired length. Here's an example in PHP:

只需构建一串随机a-z, A-Z, 0-9或任何你想要的)直到所需的长度。这是 PHP 中的一个示例:

function generatePassword($length = 8) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $count = mb_strlen($chars);

    for ($i = 0, $result = ''; $i < $length; $i++) {
        $index = rand(0, $count - 1);
        $result .= mb_substr($chars, $index, 1);
    }

    return $result;
}

To optimize, you can define $charsas a static variable or constant in the method (or parent class) if you'll be calling this function many times during a single execution.

为了优化,如果您将在一次执行期间多次调用此函数,您可以$chars在方法(或父类)中将其定义为静态变量或常量。

回答by Dolph

Here's a simple solution. It will contain lowercase letters and numbers.

这是一个简单的解决方案。它将包含小写字母和数字。

substr(str_shuffle(strtolower(sha1(rand() . time() . "my salt string"))),0, $PASSWORD_LENGTH);

Here's A stronger solution randomly generates the character codes in the desired character range for a random length within a desired range.

这是一个更强大的解决方案,随机生成所需字符范围内的字符代码,以获得所需范围内的随机长度。

function generateRandomPassword() {
  //Initialize the random password
  $password = '';

  //Initialize a random desired length
  $desired_length = rand(8, 12);

  for($length = 0; $length < $desired_length; $length++) {
    //Append a random ASCII character (including symbols)
    $password .= chr(rand(32, 126));
  }

  return $password;
}

回答by William

I want to play the game. The simplest way would be to do:

我想玩游戏。最简单的方法是:

function rand_passwd( $length = 8, $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' ) {
    return substr( str_shuffle( $chars ), 0, $length );
}

This is pretty much just a modification of the first answer. Specify the characters you want in the second parameters and the length of the password in the first.

这几乎只是对第一个答案的修改。在第二个参数中指定你想要的字符,在第一个参数中指定密码的长度。

回答by fooSolver

This is how I do it.

我就是这样做的。

$pw = ""; 
for ($i = 0; $i < 13; $i++)
{
    $pw .= chr(rand(33, 126));
}

回答by Ronan Corre

here is a function that generates a password with a minimum length, a minimum number of digits and a minimal number of letters.

这是一个生成具有最小长度、最少位数和最少字母数的密码的函数。

function generatePassword() {
$min_length=8;  //Minimum length of the password
$min_numbers=2; //Minimum of numbers AND special characters
$min_letters=2; //Minimum of letters

$password = '';
$numbers=0;
$letters=0;
$length=0;

while ( $length <= $min_length OR $numbers <= $min_numbers OR $letters <= $min_letters) {
    $length+=1;
    $type=rand(1, 3);
    if ($type==1) {
        $password .= chr(rand(33, 64)); //Numbers and special characters
        $numbers+=1;
    }elseif ($type==2) {
        $password .= chr(rand(65, 90)); //A->Z
        $letters+=1;
    }else {
        $password .= chr(rand(97, 122)); //a->z
        $letters+=1;
    }

}
return $password;   
}

回答by Raphael Ndwigah

A good password should be a mixture of both uppercase, lowercase, has number, letters, has special characters and its more than 6 characters long. Here is function I use on my apps.

一个好的密码应该是大写、小写、数字、字母、特殊字符和长度超过 6 个字符的混合。这是我在我的应用程序上使用的功能。

function randomPassword( $length = 8 ) 
{ 
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-=+;:,.?"; 
$length = rand(10, 16); 
$password = substr( str_shuffle(sha1(rand() . time()) . $chars ), 0, $length );
 return $password;
}

回答by Dave Vogt

Another, very simple (and secure!) way to do this is the following (I generate all my own passwords that way):

另一种非常简单(且安全!)的方法如下(我以这种方式生成所有自己的密码):

base64_encode(random_bytes(12));

This generates a 16 character password that uses quite a sane range of characters.

这会生成一个 16 个字符的密码,该密码使用相当合理的字符范围。

However, depending on your requirements (for example if a user needs to type in their password), it may be desirable to remove characters that migth be confused (such as l, I, 1, 0, O, 5, S, and so on). In that case, the above solution is probably a bit too simple.

但是,根据您的要求(例如,如果用户需要输入他们的密码),可能需要删除可能会混淆的字符(例如 l、I、1、0、O、5、S 等在)。在那种情况下,上面的解决方案可能有点太简单了。

回答by Jaspreet Chahal

Also you can try a function that I wrote and is available form my blog. Advantage of this function is that it gives equal importance to lowercase, uppercase, numbers and special characters. It can be found here PHP random password generator function

您也可以尝试我编写的一个函数,该函数可从我的博客中获得。此功能的优点是它对小写、大写、数字和特殊字符给予同等重视。可以在这里找到 PHP 随机密码生成器函数

回答by jave.web

I like to shuffle array of random chars

我喜欢打乱随机字符数组

$a = str_split("abcdefghijklmnopqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXY0123456789");
shuffle($a);
echo implode($a); //maxlength
echo "\n".substr( implode($a), 0, 10 ); //instead of 10 => any length

//As function:
function getMeRandomPwd($length){
    $a = str_split("abcdefghijklmnopqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXY0123456789"); 
    shuffle($a);
    return substr( implode($a), 0, $length );
}
echo "\n".getMeRandomPwd(8)."\n".getMeRandomPwd(11);
// Outpus something like:
// 3Ai4Xf6R2I8bYGUmKgB9jpqo7ncV5teuQhkOHJCNrTP0sLFd1wxSMlEWvyaD
// 3Ai4Xf6R2I
// JsBKWFDa
// gfxsjr3dX70

If you need the password to be longer, just concatenate charlist a few times :)

如果您需要更长的密码,只需将字符列表连接几次:)

回答by Eugene Mala

This function will generate more stronger password than most woted solution:

此函数将生成比大多数 woted 解决方案更强大的密码:

function generatePassword($size=8){
    $p = openssl_random_pseudo_bytes(ceil($size*0.67), $crypto_strong);
    $p = str_replace('=', '', base64_encode($p));
    $p = strtr($p, '+/', '^*');
    return substr($p, 0, $size);      
}

Each character of password will be [A-Z] or [a-z] or ^ or *

密码的每个字符将是 [AZ] 或 [az] 或 ^ 或 *