php tutorial - Strong PHP Password Generator Script - php programming - learn php - php code - php script



PHP password generator is an integrated, working random password generation function for PHP. This blog post concerns how to generate online secure and strong random password via PHP and to mail it to anybody’s email ID when they forgot their password.

Also, once the user log in to his/her account using auto-generated password, they would be asked to change their password for the first time. We have applied sha1() function for PHP password encryption that store and only allows authentic users to login and access a specific web page.

In our example, our objectives is to generate passwords in PHP :

  • Generating strong and secure random password for a user and mailing it to his/her email ID.
// Generating Password
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*_";
$password = substr( str_shuffle( $chars ), 0, 8 );
click below button to copy the code. php tutorial - team

  • User is allowed to Login using same password (which is emailed earlier).
  • If, user forgot his password, then newly auto generated password will be send on his/her mail account.
// Generating New password as done in above function and Update it in database by below query
$password1= sha1($password); //Encrypting Password
$query = mysql_query("UPDATE registration SET password='$password1' WHERE email='$email'");
if($query){
$to = $email;
$subject = 'Your New Password...';
$message = 'Hello User
Your new password : '.$password.'
E-mail: '.$email.'
Now you can login with this email and password.';
/* Send the message using mail() function */
if(mail($to, $subject, $message ))
{
echo "New Password has been sent to your mail, Please check your mail and SignIn.";
}
click below button to copy the code. php tutorial - team

  • After successful login, a session will be created for user then, user can change his/her auto-generated password online.
$_SESSION['login_user']=$email;//Initializing Session with user email
click below button to copy the code. php tutorial - team

We have also used MySQL database to store user generated password.

Watch our live demo or download our code to use the PHP Password Generator.

 php-password-generator

Learn php - php tutorial - php-password-generator - php examples - php programs

Complete HTML and PHP codes are given below.

PHP file: password_form.php

Given below our complete HTML for login form.

<?php include 'password_generator.php'; ?>
<!DOCTYPE html>
<html>
<head>
<title>PHP Password Generator</title>
<link href="css/password.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="main">
<h2>PHP Password Generator</h2>
<form action="password_form.php" method="post">
<label class="heading">Name :</label>
<input name="name" type="text">
<span class="error"><?php echo $nameError;?></span>
<label class="heading">Email :</label>
<input name="email" type="text">
<span class="error"><?php echo $emailError;?></span>
<input name="submit" type="submit" value="SignUp">
<span class="success"><?php echo $successMessage;?></span>
<span class="success"><?php echo $passwordMessage;?></span>
</form>
<p><b>Note :</b> Fill this form and password will be send to your email address.</p>
<a class="login" href="password_login.php">SignIn</a>
</div>
</div>
</body>
</html>
click below button to copy the code. php tutorial - team

PHP file: password_generator.php

In the below script, we validate all fields and then mail the generated password. We have also applied sha1() encryption function to store encrypted password in database.

<?php
// Initialize Variables To Null.
$name =""; // Sender's Name
$email =""; // Sender's Email ID
$nameError ="";
$emailError ="";
$successMessage ="";
$passwordMessage ="";
//On Submitting Form Below Function Will Execute
if(isset($_POST['submit']))
{
// Checking Null Values In Message
if (!($_POST["name"]== "")){
$name = $_POST["name"];
// Check Name Only Contains Letters And Whitespace
if (preg_match("/^[a-zA-Z ]*$/",$name)){
if (!($_POST["email"]=="")) {
$email =$_POST["email"]; // Calling Function To Remove Special Characters From Email
// Check If E-mail Address Syntax Is Valid Or Not
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Sanitizing Email(Remove Unexpected Symbol like <,>,?,#,!, etc.)
if (filter_var($email, FILTER_VALIDATE_EMAIL)){
// Generating Password
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*_";
$password = substr( str_shuffle( $chars ), 0, 8 );
$password1= sha1($password); //Encrypting Password
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection With Server..
$db = mysql_select_db("college", $connection); // Selecting Database
$result = mysql_query("SELECT * FROM registration WHERE email='$email'");
$data = mysql_num_rows($result);
if(($data)==0){
// Insert query
$query = mysql_query("insert into registration(name, email, password) values ('$name', '$email', '$password1')");
if($query){
$to = $email;
$subject = 'Your registration is completed';
/* Here Prepare The Message For The E-mail */
$message = 'Hello'.$name.'
Your email and password is following:
E-mail: '.$email.'
Your new password : '.$password.'
Now you can login with this email and password.';
/* Send The Message Using mail() Function */
if(mail($to, $subject, $message ))
{
$successMessage = "Password has been sent to your mail, Please check your mail and SignIn.";
}
}
}
else{
$emailError = "This email is already registered, Please try another email...";
}
}
else{
$emailError = "Invalid Email"; }
}
else{
$emailError = "Email is required";
}
}
else{
$nameError = "Only letters and white space allowed";
}
}
else {
$nameError = "Name is required";
}
}
?>
click below button to copy the code. php tutorial - team

PHP file: password_login.php

Given below our complete HTML for login form.

<?php include 'login_validation.php'; ?>
<!DOCTYPE html>
<html>
<head>
<title>PHP Login Form</title>
<link href="css/password.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="main">
<h2>PHP Login Form</h2>
<form action="password_login.php" method="post">
<label class="heading">Email :</label>
<input name="email" type="text">
<label class="heading">Password :</label>
<input name="password" type="password">
<input name="submit" type="submit" value="SignIn">
<span class="error"><?php echo $Error;?></span>
<span class="success"><?php echo $successMessage;?></span>
</form><a class="forgot" href="forgot_password.php">forgot password ?</a>
<a class="login" href="password_form.php">SignUp</a>
</div>
</div>
</body>
</html>
click below button to copy the code. php tutorial - team

PHP file: login_validation.php

In the below script, we validate all fields and then, verifies entered email, if, it exists in database then, session will be created for this email.

<?php
session_start(); // Starting Session
$Error =""; // Initialize Variables To Null.
$successMessage ="";
if (isset($_POST['submit']))
{
if ( !( $_POST['email'] == "" && $_POST['password'] == "" ) )
{
$email=$_POST['email']; // Fetching Values From URL
$password= sha1($_POST['password']); // Password Encryption, If you like you can also leave sha1
$email = filter_var($email, FILTER_SANITIZE_EMAIL); // Sanitizing E-mail(Remove unexpected symbol like <,>,?,#,!, etc.)
if (filter_var($email, FILTER_VALIDATE_EMAIL)) // Check if E-mail Address Syntax is Valid or Not
{
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("college", $connection); // Selecting Database
// Matching User Input E-mail and Password with stored E-mail and Password in Database
$result = mysql_query("SELECT * FROM registration WHERE email='$email' AND password='$password'");
$data = mysql_num_rows($result);
if($data==1){
$_SESSION['login_user']=$email; // Initializing Session
header('Location: profile.php');
}
else{
$Error ="Email or Password is wrong...!!!!";
}
mysql_close ($connection); // Connection Closed
}
else{
$Error ="Invalid Email Format....!!!!";
}
}
else{
$Error ="Email or Password is Empty...!!!!";
}
}
?>
click below button to copy the code. php tutorial - team

PHP file: profile.php

Given below our complete HTML for user profile page, here user can change his password.

<?php include 'profile_validation.php'; ?>
<!DOCTYPE html>
<html>
<head>
<title>PHP Profile Page</title>
<link href="css/password.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="main">
<h2>Welcome ! <i><?php echo $login_session; ?></i></h2>
<form action="profile.php" method="post">
<a class="logout" href="logout.php">SignOut</a>
<h3>Now you can change password.</h3><label>New Password :</label>
<input name="newpassword" type="password">
<label>Confirm New Password :</label>
<input name="cnewpassword" type="password">
<input name="submit" type="submit" value="Change Password">
<span class="error"><?php echo $Error;?></span>
<span class="success"><?php echo $successMessage;?></span>
</form>
</div>
</body>
</html>
click below button to copy the code. php tutorial - team

PHP file: profile_validation.php

In the below script, we validate all fields and then, update password field in Database for the same user.

<?php
include('session.php');
$Error ="";  // Initialize Variables to Null.
$successMessage ="";
if (isset($_POST['submit']))
{
if ( !($_POST['newpassword'] == "" && $_POST['cnewpassword'] == "" ))
{
$newpassword=$_POST['newpassword'];  // Fetching Values from URL
$cnewpassword=$_POST['cnewpassword'];
if( $newpassword == $cnewpassword )
{
$password= sha1($cnewpassword);
$connection = mysql_connect("localhost", "root", "");  // Establishing Connection with Server..
$db = mysql_select_db("college", $connection);  // Selecting Database
$query = mysql_query("UPDATE registration SET password='$password' WHERE password='$login_password'");
if($query)
{
$successMessage ="Password Changed Successfully.";
}
}
else{
$Error ="Password not match...!!!!";
}
}
else{
$Error ="Password should not be empty....!!!!";
}
}
?>
click below button to copy the code. php tutorial - team

PHP file: session.php

In the below script, user details get fetched from database by passing session in SQL query.

<?php
//  Establishing Connection with Server by Passing server_name, user_id and password as a Parameter.
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("college", $connection);  // Selecting Database
session_start();  // Starting Session
$email_check=$_SESSION['login_user'];  // Storing Session
//  SQL Query to Fetch Complete Information of User.
$ses_sql=mysql_query("select * from registration where email='$email_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['name'];
$login_password =$row['password'];
if(!isset($login_session))
{
mysql_close($connection); // Closing Connection
header('Location: password_login.php'); // Redirecting to Home Page
}
?>
click below button to copy the code. php tutorial - team

PHP file: forgot_password.php

Given below our complete HTML for forgot password page, here user put his email and newly generated password will sent on his email.

<?php include 'forgot_password_generate.php'; ?>
<!DOCTYPE html>
<html>
<head>
<title>PHP Forgot Password</title>
<link href="css/password.css" rel="stylesheet">
</head>
<body>
<div class="container main">
<h2>Forgot Password</h2>
<form action="forgot_password.php" method="post">
<label class="heading">Email :</label>
<input name="email" type="text">
<input name="submit" type="submit" value="Resend Password">
<span class="error"><?php echo $Error;?></span>
<span class="success"><?php echo $successMessage;?></span>
</form>
<p><b>Note :</b> Enter your email, password will be send to your email address.</p>
<a class="login" href="password_login.php">SignIn</a>
</div>
</body>
</html>
click below button to copy the code. php tutorial - team

PHP file: forgot_password_generate.php

In the below script, we validate all fields and then mail the newly generated password. We have also applied sha1() encryption function to Update encrypted password in database.

<?php
// Initialize Variables to Null.
$email =""; // Senders E-mail ID
$Error ="";
$successMessage ="";
// On Submitting Form Below Function Will Execute
if(isset($_POST['submit']))
{
if (!($_POST["email"]==""))
{
$email =$_POST["email"];  // Calling Function To Remove Special Characters From E-mail
$email = filter_var($email, FILTER_SANITIZE_EMAIL);  // Sanitizing E-mail(Remove unexpected symbol like <,>,?,#,!, etc.)
if (filter_var($email, FILTER_VALIDATE_EMAIL))
{
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*_"; // Generating Password
$password = substr( str_shuffle( $chars ), 0, 8 );
$password1= sha1($password);
$connection = mysql_connect("localhost", "root", "");  // Establishing Connection With Server..
$db = mysql_select_db("college", $connection);  // Selecting Database
$query = mysql_query("UPDATE registration SET password='$password1' WHERE email='$email'");
if($query)
{
$to = $email;
$subject = 'Your New Password...';
// To Prepare The Message For E-mail.
$message = 'Hello User
Your new password : '.$password.'
E-mail: '.$email.'
Now you can login with this email and password.';
// Send The Message Using mail() Function.
if(mail($to, $subject, $message ))
{
$successMessage = "New Password has been sent to your mail, Please check your mail and SignIn.";
}
}
}
else{
$Error = "Invalid Email";
}
}
else{
$Error = "Email is required";
}
}
?>
click below button to copy the code. php tutorial - team

PHP file: logout.php

In the below script, all sessions will be destroyed and user get redirected to home page i.e. login.php page.

<?php
session_start();
if(session_destroy()) // Destroying All Sessions
{
header("Location: password_login.php"); // Redirecting to Home Page
}
?>
click below button to copy the code. php tutorial - team

CSS File: password.css

Styling HTML elements.

@import "http://fonts.googleapis.com/css?family=Raleway";
/* Above line is used for online google font */
h2{
background-color:#FEFFED;
padding:30px 35px;
margin:-10px -50px;
text-align:center;
border-radius:10px 10px 0 0
}
h3{
font-size:21px;
margin-bottom:40px;
color:#000;
font-family:serif
}
hr{
margin:10px -50px;
border:0;
border-top:1px solid #ccc;
margin-bottom:40px
}
p{
font-size:14px
}
i{
color:#07b300;
font-weight:700
}
b{
color:red;
font-weight:700;
font-size:16px
}
span{
color:red
}
.forgot{
text-decoration:none;
display:block;
float:left;
margin-top:5px;
margin-left:5px;
color:blue
}
.logout{
text-decoration:none;
color:red;
background-color:#e6e6fa;
padding:5px 12px;
border:1px solid #8a2be2;
float:right;
border-radius:0 0 0 5px;
margin-top:-40px;
margin-right:-50px;
font-size:12px;
font-weight:700
}
.login{
float:right;
text-align:center;
text-decoration:none;
color:#000;
font-weight:700;
width:25%;
padding:5px;
background-color:#f5f5dc;
border:1px solid gray;
border-radius:5px;
outline:none
}
.success{
color:green;
display:block;
font-weight:700
}
div.container{
width:900px;
height:610px;
margin:35px auto;
font-family:'Raleway',sans-serif
}
div.main{
width:320px;
padding:10px 50px 25px;
border:2px solid gray;
border-radius:10px;
font-family:raleway;
float:left;
margin-top:60px
}
input[type=text],input[type=password]{
width:95.7%;
height:30px;
padding:5px;
margin-bottom:5px;
margin-top:5px;
border:2px solid #ccc;
color:#4f4f4f;
font-size:16px;
border-radius:5px
}
label{
color:#464646;
text-shadow:0 1px 0 #fff;
font-size:14px;
font-weight:700
}
input[type=submit]{
padding:10px;
font-size:18px;
background:linear-gradient(#ffbc00 5%,#ffdd7f 100%);
border:1px solid #e5a900;
color:#4E4D4B;
font-weight:700;
cursor:pointer;
width:100%;
border-radius:5px;
margin-bottom:10px
}
input[type=submit]:hover{
background:linear-gradient(#ffdd7f 5%,#ffbc00 100%)
}
click below button to copy the code. php tutorial - team


Related Searches to Strong PHP Password Generator Script