PHP secure random password generator
In this article, you will learn how to generate random password in PHP and encrypt it before storing it in the database and sending it to the user's mail inbox.
If you are developing or wish to develop an application that provides users with unique, strong passwords. Definitely, you should use the right method to generate a random password and also use strong password encryption techniques. PHP provides many random number generator functions, like rand(), mt_rand(), and random_int(), but that is not enough. As the developers are using modern technology to advance their applications, the attackers are also using advanced hacking techniques. This results in a large number of web application vulnerabilities. So, let's find the best way to generate a PHP random password and encrypt it using a strong password hashing technique.
At the very first step, create a PHP file, 'index.php', that contains an HTML form. The form contains three fields for 'Fullname', 'Username', and 'Email' input. We are using bootstrap CSS for providing a better interface and HTML5 validation for validating the input fields.
1. index.php
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>PHP secure random password generator</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<form method="post" class="form-horizontal" action="handler.php" >
<div class="form-group">
<label class="col-md-3 control-label">Full name</label>
<div class="col-md-6">
<input type="text" class="form-control" name="fullName" required />
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Email</label>
<div class="col-md-6">
<input type="text" class="form-control" name="email" placeholder="Enter a valid email address" required />
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Username</label>
<div class="col-md-6">
<input type="text" class="form-control" name="username" required />
</div>
</div>
<div class="form-group">
<div class="col-md-9 col-md-offset-3">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</body>
</html>
Next, we create another PHP file, 'handler.php' and get all the input field data in $_POST. To generate a random password, first we take the character range ($chars) from which we take the random character for password and shuffle these characters using the str_shuffle() function, and then we set the password length in the substr() function.
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*_";
$password = substr( str_shuffle( $chars ), 0, 8 );
We cannot store the password as it is in the database. Therefore, it is important to encrypt them. PHP provides many password hashing functions. In this article, we are using password_hash() to encrypt the password using a PASSWORD_ARGON2I password algorithm.
// Encrypt password
$password = password_hash($password, PASSWORD_ARGON2I);
Here is the complete code of 'handler.php'. When the user submits the form, it redirects to this file , stores the generated password in the database, and sends the password mail to the user.
2. handler.php
<?php
$name = $_POST['fullName'];
$email = $_POST['email'];
$username = $_POST['username'];
// Generate Random Password
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*_";
$password = substr( str_shuffle( $chars ), 0, 8 );
// Encrypt password
$password = password_hash($password, PASSWORD_ARGON2I);
$conn = new mysqli('hostname', 'username', 'password', 'databasename');
//Check for connection error
if($conn->connect_error){
die("Error in DB connection: ".$conn->connect_errno." : ".$conn->connect_error);
}
$insert = 'INSERT INTO `users` (`uid`, `fullname`, `email`, `username`, `password`)
VALUES (`uid`, "'.$name.'", "'.$email.'", "'.$username.'", "'.$password.'")';
if(mysqli_query($conn, $insert)){
// Send password in mail
$subject = "Please login with given credentials.";
$headers = 'From: '.$from.'\r\n';
$message = "Hello, ".$name."\r\n"
." Please login with this credentials"."\r\n"
." Username: ".$username."\r\n"
." Password: ".$password;
$mailsent = mail($email, $subject, $message, $headers);
}
header("Location: index.php");
?>
Related Articles
How to add google reCAPTCHA v2 in registration form using PHPComplete HTML Form Validation in PHP
How to display PDF file in PHP from database
How to read CSV file in PHP and store in MySQL
Create And Download Word Document in PHP
PHP SplFileObject Standard Library
Simple File Upload Script in PHP
Sending form data to an email using PHP
Recover forgot password using PHP and MySQL
Php file based authentication
Simple PHP File Cache
How to get current directory, filename and code line number in PHP
PHP7 Password Hashing
PHP7 Sodium Encryption Decryption
PHP user registration & login/ logout with secure password encryption
Recover forgot password using PHP and MySQL
How to store Emoji character in MySQL using PHP
PHP File Upload MIME Type Validation with Error Handler
File Upload Validation in PHP
Simple File Upload Script in PHP
jQuery file upload progress bar
Simple star rating system using PHP, jQuery and Ajax