Several methods to generate random passwords in php (1/2)_PHP tutorial

WBOY
Release: 2016-07-13 16:59:11
Original
933 people have browsed it

mt_rand (int $min, int $max) function is used to generate random integers, where $min–$max is the range of ascii code, here it is 33-126, the range can be adjusted as needed, such as ascii code Bits 97–122 in the table correspond to the English letters a–z. For details, please refer to the ascii code table; the chr (int $ascii) function is used to convert the corresponding integer $ascii into the corresponding character.

Code:

function create_password($pw_length = 8)
{
$randpwd = '';
for ($i = 0; $i < $pw_length; $i++)
{
           $randpwd .= chr(mt_rand(33, 126));
}
Return $randpwd;
}
// Call this function and pass the length parameter $pw_length = 6
echo create_password(6);


Method 2:

1. Preset a string $chars, including a–z, a–z, 0–9 and some special characters;

2. Randomly pick a character from the $chars string;

3. Repeat the second step n times to get a password of length n.

Code:

function generate_password( $length = 8 ) {
// Password character set, you can add any characters you need
$chars = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_ []{}<>~`+=,.;:/?|';
$password = '';
for ( $i = 0; $i < $length; $i++ )
{
// There are two ways to obtain characters
// The first is to use substr to intercept any character in $chars;
                                                                                                                                                                                                                             is to take any element of the character array $chars
// $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
           $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
}
Return $password;
}

1 2

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631355.htmlTechArticlemt_rand ( int $min , int $max ) function is used to generate random integers, where $min$max is ascii The range of the code, here is 33-126, you can adjust the range as needed, for example, 97122 bits in the ascii code table corresponds to...
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template