PHP to generate random username and password implementation code _php tips

Source: Internet
Author: User
Tags rand

Sometimes we need to use randomly generated username and password in the application, which can greatly improve the security of the application, generate random username and password in PHP can use the Mt_rand function or the RAND function, the RAND function has more application in the verification code, and the random code of the growth character usually needs the Mt_rand function.

Using PHP to generate random numbers can be applied in many places, such as designing random passwords for programs, simulating dice game applications, stone-and-scissors-game applications, and more.

The following is a two-function method for generating random numbers in PHP:

Copy Code code as follows:

Automatically generate user names randomly for users (length 6-13)
function Create_password ($PW _length = 4) {
$randpwd = ';
for ($i = 0; $i < $PW _length; $i + +) {
$randpwd. = Chr (Mt_rand (33, 126));
}
return $randpwd;
}
function Generate_username ($length = 6) {
Password character set, you can add any character you need
$chars = ' abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&* ()-_ []{}<>~ ' +=,.;:/?| ';
$password = ';
for ($i = 0; $i < $length; $i + +)
{
Here are two ways to get a character
The first is to use SUBSTR to intercept any one character in the $chars;
The second is any element that takes the $chars of a character array
$password. = substr ($chars, Mt_rand (0, strlen ($chars)-1), 1);
$password. = $chars [Mt_rand (0, strlen ($chars)-1)];
}
return $password;
}
Call this function
$userId = ' user '. Generate_username (6);
$pwd = Create_password (9);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.