In this tutorial, I am going to show you how you can make sign in & sign up form fully functional with PHP and MySql. PHP use as a back-end language and MySql as a Database. Where we store users data. It is a complete tutorial where you can find sign in, sign up and forgot password forms.
Demo User: demo@demo.com
Demo Password: demo
First of all you need to understand how to create sign up and sign in form with Bootstrap 4 or you can check the below post where we create sign in and sign up form using bootstrap 4 with HTML5 validation.
Bootstrap 4 is world famous design frame work that is why we create this example with bootstrap 4.
For jQuery validation & background image change consider below snippet. You will find all js script in form-script.js file.
// For background image change
$(function(){
var images=[
'https://images.pexels.com/photos/1558732/pexels-photo-1558732.jpeg',
'https://images.pexels.com/photos/1287075/pexels-photo-1287075.jpeg',
'https://images.pexels.com/photos/326055/pexels-photo-326055.jpeg'
];
setInterval(function(){
var url = images[Math.floor(Math.random() * images.length)];
$("body").css({'background':'url('+url+') no-repeat center center fixed','background-size':'cover cover','body':'100vh'});
},5000);
$('[data-toggle="tooltip"]').tooltip();
});
// Form Validation & Ajax Request code below
function formValidate(formId,formMsg){
var flag = 0;
$(formId).find('[data-required]').each(function(){
if($(this).val()===""){
$(this).addClass('is-invalid');
flag = 1;
}else{
$(this).removeClass('is-invalid');
$(this).addClass('is-valid');
$(formMsg).html('');
}
});
if(flag==1){
$(formMsg).html('<div class="text-danger"><i class="fa fa-exclamation-circle"></i> Asterisk fields are mandatory! </div>');
return false;
}
$(".overlay").show();
$(".overlay").html('<div class="text-light"><span class="spinner-grow spinner-grow-sm" role="status"></span> Please wait...!</div>');
setTimeout(function(){$(".overlay").hide()},800);
$.ajax({
type:'POST',
url:'ajax/action-form.php',
data:$(formId).serialize(),
success: function(data){
setTimeout(function(){$(".overlay").hide()},800);
var a = data.split('|***|');
if(a[1]==1){
$(formMsg).html(a[0]);
if(typeof(a[2]) != "undefined" && a[2] !== null) {
setTimeout(function(){window.location.href=""+a[2]},800);
}
}else{
$(formMsg).html(a[0]);
}
}
});
}
In this post I am using Database Class. You can download DB Class from here. The POD connection is given below.
Config file snippet is below.
<?php
session_start();
include_once('includes/Database.php');
include_once('includes/class.phpmailer.php');
include_once('includes/class.smtp.php');
define('DB_NAME', 'learncodeweb_demo');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
/**
** Change below url with your url
**/
define('HOME_URL','http://localhost/YOUR-URL/',true);
$dsn = "mysql:dbname=".DB_NAME.";host=".DB_HOST."";
$pdo = "";
try {
$pdo = new PDO($dsn, DB_USER, DB_PASSWORD);
}catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$db = new Database($pdo);
$mail = new PHPMailer;
/*
*** You can set SMTP if you want
*** Change below code as per your need
*/
/*
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->SMTPDebug = 2; // debugging: 1 = errors and messages, 2 = messages only
$mail->Host = 'YOUR_HOST'; // Specify main and backup server
$mail->Port = 587; // Set the SMTP port
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'YOUR@EMAIL.COM'; // SMTP username
$mail->Password = 'YOUR_PASS'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
*/
?>
In this tutorial I am using Bootstrap tabs you can visit this link to understand how to use bootstrap 4 tab.
The sign in and sign up form PHP script is given below. On user sign up an email shot to the user with confirmation link. For email consider PHPMailer a PHP library.
Sign In Form script.
if(isset($_REQUEST['signinname']) and $_REQUEST['signinname']!=""){
extract($_REQUEST);
$getUsers = $db->getAllRecords('tb_user','id,username,useremail,userpassword',' AND ((useremail="'.$signinname.'") OR (username="'.$signinname.'")) AND userstatus=1 ');
if(isset($getUsers[0]['userpassword']) and $getUsers[0]['userpassword']!=""){
/*
** Get and varify user password
*/
$hash = $getUsers[0]['userpassword'];
if(password_verify($signinpassword, $hash)){
$_SESSION['id'] = $getUsers[0]['id'];
$_SESSION['name'] = $getUsers[0]['username'];
echo '<div class="alert alert-success p-1 mt-1"><i class="fa fa-fw fa-thumbs-up"></i> Login successfully <strong>Please wait..!</strong></div>|***|1|***|home.php';
exit;
} else {
echo '<div class="alert alert-danger p-1 mt-1"><i class="fa fa-fw fa-exclamation-triangle"></i> Invalid password!</div>|***|0';
exit;
}
}else{
echo '<div class="alert alert-danger p-1 mt-1"><i class="fa fa-fw fa-exclamation-triangle"></i> User not exist or not varified!</div>|***|0';
exit;
}
}
Sign Up Form Script
if(isset($_REQUEST['signupemail']) and $_REQUEST['signupemail']!=""){
extract($_REQUEST);
$getUsers = $db->getQueryCount('tb_user','id',' AND ((useremail="'.$signupemail.'") OR (username="'.$signupusername.'")) ');
if($getUsers[0]['total']){
echo '<div class="alert alert-danger p-1 mt-1"><i class="fa fa-fw fa-exclamation-triangle"></i> User already exist!</div>|***|0';
exit;
}
$termcondition = '';
if(isset($signupcondition)){
$termcondition = 1;
}
if($signuppassword!=$signupcpassword){
echo '<div class="alert alert-danger p-1 mt-1"><i class="fa fa-fw fa-exclamation-triangle"></i> Passwords does not match!</div>|***|0';
exit;
}
if($termcondition==""){
echo '<div class="alert alert-danger p-1 mt-1"><i class="fa fa-fw fa-exclamation-triangle"></i> Agree with the Terms & Conditions!</div>|***|0';
exit;
}
if(!filter_var($signupemail,FILTER_VALIDATE_EMAIL)){
echo '<div class="alert alert-danger p-1 mt-1"><i class="fa fa-fw fa-exclamation-triangle"></i> Email address is not valid!</div>|***|0';
exit;
}
$token = md5(uniqid('lcw-'.mt_rand(),true));
$tokenUrl = home_url.'varify.php?token='.$token;
/*
*** Creating hash with cost 12
*** You can change or can ignore cost as per your need
*/
$options = array('cost' => 12);
$hash = password_hash($signuppassword, PASSWORD_BCRYPT, $options);
$data = array(
'useremail'=>$signupemail,
'username'=>$signupusername,
'userpassword'=>$hash,
'termcondition'=>$signupcondition,
'userstatus'=>0,
'token'=>$token
);
$insert = $db->insert('tb_user',$data);
if($insert){
/*
** Email sent to register user
*/
$body = '<table bgcolor="#FFFFFF" width="560" style="border:1px solid #ccc; opacity:0.8; font-family:Arial; font-size:14px; line-height:18px;" cellspacing="0" cellpadding="5" border="0" align="center">
<tbody>
<tr>
<td align="center"><strong style="color:#55BDE8; font-size:3em; font-weight:bolder; text-align:center; margin:0px;">THANK YOU</strong><br /><br /></td>
</tr>
<tr>
<td align="center"><span style="color:#000; font-size:2.2em; text-align:center; margin:0px;">for your registration</span></td>
</tr>
<tr>
<td style="color:#4da6e1; font-size: 25px; padding-bottom: 10px; border-bottom: 1px solid #000;">Dear '.$signupusername.',</td>
</tr>
<tr>
<td valign="top" align="left">
<p style="color:#000; font-size: 29px; font-weight: normal; margin:15px 0px;">Thank you for</p>
<p style="color:#000; font-size: 29px; font-weight: normal; margin:15px 0px;">signing up for the free</p>
<p style="color:#50BBE7; font-size: 29px;font-weight: normal; margin:15px 0px;">LearnCodeWeb Account.</p>
</td>
</tr>
<tr>
<td valign="top" align="left">
<p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.<br>You can contact us any time by</p>
</td>
</tr>
<tr>
<td align="center"><a href="https://learncodeweb.com/themeforest/varify.php?token='.$token.'" style=" background: #007bff; color: #fff; padding: 10px; border-radius: 5px; border: 4px solid #0167d4;" target="_blank">Activate Your Account</a></td>
</tr>
<tr>
<td width="100%" valign="middle" align="center" style="text-align: center; width: 100%; padding: 5px; color:#FFF; height:60px; background:linear-gradient(to bottom, #33BDBE 0, #06184d 100%);">
<p style="font-size: 14px; padding-top: 10px;">
<a style="color: #fff;text-decoration:none;" href="" target="_blank">Terms of Use</a> |
<a style="color: #fff;text-decoration:none;" href="" target="_blank">Privacy Policy</a> |
<a style="color: #fff;text-decoration:none;" href="" target="_blank">Licensing & Compliance</a>
</p>
</td>
</tr>
</tbody>
</table>';
$name = 'Learn Code Web';
$email = 'noreply@learncodeweb.com';
$to = $signupemail;
$header = "From: \"".$name."\" <".$email."> \n";
$header .= "To: \"".$name."\" <".$to."> \n";
$header .= "Return-Path: <".$email."> \n";
$header .= "MIME-Version: 1.0\n";
$header .= "Content-Type: text/HTML; charset=ISO-8859-1 \n";
$subject = 'NEW REGISTRATION';
$mail = mail($to,$subject,$body,$header);
if(!$mail) {
echo '<div class="alert alert-danger p-1 mt-1"><i class="fa fa-fw fa-exclamation-triangle"></i> User created but email not send!</div>|***|0';
exit;
}else{
echo '<div class="alert alert-success p-1 mt-1"><i class="fa fa-fw fa-thumbs-up"></i> Success message goes here!</div>|***|1|***|index.php';
exit;
}
}else{
echo '<div class="alert alert-danger p-1 mt-1"><i class="fa fa-fw fa-exclamation-triangle"></i> Error message goes here!</div>|***|0';
exit;
}
}
Change password script is given below just copy past all PHP snippets in action-form.php. Download example you will find this file within ajax folder.
Forgot password script
if(isset($_REQUEST['forgotemail']) and $_REQUEST['forgotemail']!=""){
extract($_REQUEST);
$getUsers = $db->getAllRecords('tb_user','*',' AND ((useremail="'.$forgotemail.'") OR (username="'.$forgotemail.'")) ');
if(isset($getUsers[0]['id']) and $getUsers[0]['id']!=""){
$token = md5(uniqid('lcw-'.mt_rand(),true));
$update = $db->update('tb_user',array('token'=>$token),array('id'=>$getUsers[0]['id']));
$tokenUrl = home_url.'password.php?token='.$token;
/*
** Email sent to register user
*/
$body = '<table bgcolor="#FFFFFF" width="560" style="border:1px solid #ccc; opacity:0.8; font-family:Arial; font-size:14px; line-height:18px;" cellspacing="0" cellpadding="5" border="0" align="center">
<tbody>
<tr>
<td align="center"><strong style="color:#55BDE8; font-size:3em; font-weight:bolder; text-align:center; margin:0px;">PASSWORD UPDATED</strong><br /><br /></td>
</tr>
<tr>
<td><strong>Request</strong></td>
</tr>
<tr>
<td style="color:#4da6e1; font-size: 25px; padding-bottom: 10px; border-bottom: 1px solid #000;">Dear '.isset($getUsers[0]['username'])?$getUsers[0]['username']:'User'.',</td>
</tr>
<tr>
<td valign="top" align="left">
<p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.<br>You can contact us any time by</p>
</td>
</tr>
<tr>
<td align="center"><a href="" style=" background: #007bff; color: #fff; padding: 10px; border-radius: 5px; border: 4px solid #0167d4; text-decoration:none;" target="_blank">Change Password</a></td>
</tr>
<tr>
<td width="100%" valign="middle" align="center" style="text-align: center; width: 100%; padding: 5px; color:#FFF; height:60px; background:linear-gradient(to bottom, #33BDBE 0, #06184d 100%);">
<p style="font-size: 14px; padding-top: 10px;">
<a style="color: #fff;text-decoration:none;" href="" target="_blank">Terms of Use</a> |
<a style="color: #fff;text-decoration:none;" href="" target="_blank">Privacy Policy</a> |
<a style="color: #fff;text-decoration:none;" href="" target="_blank">Licensing & Compliance</a>
</p>
</td>
</tr>
</tbody>
</table>';
$name = 'Learn Code Web';
$email = 'help@learncodeweb.com';
$to = $getUsers[0]['useremail'];
$header = "From: \"".$name."\" <".$email.">\n";
$header .= "To: \"".$name."\" <".$to.">\n";
$header .= "Return-Path: <".$email.">\n";
$header .= "MIME-Version: 1.0\n";
$header .= "Content-Type: text/HTML; charset=ISO-8859-1\n";
$subject = 'FORGET PASSWORD';
$mail = mail($to,$subject,$body,$header);
if(!$mail) {
echo '<div class="alert alert-danger p-1 mt-1"><i class="fa fa-fw fa-exclamation-triangle"></i> Email not send!</div>|***|0';
exit;
}else{
echo '<div class="alert alert-success p-1 mt-1"><i class="fa fa-fw fa-thumbs-up"></i> Cheack you email!</div>|***|1|***|index.php';
exit;
}
}else{
echo '<div class="alert alert-danger p-1 mt-1"><i class="fa fa-fw fa-exclamation-triangle"></i> Invalid user!</div>|***|0';
exit;
}
}
To store data in MySql you need to create a table with below query. Consider below query to create tb_user. On user sign up all data will be stored in tb_user table in MySql.
MySql Queries
--
-- Table structure for table `tb_user`
--
CREATE TABLE `tb_user` (
`id` int(11) NOT NULL,
`useremail` varchar(128) NOT NULL,
`username` varchar(32) NOT NULL,
`userpassword` varchar(128) NOT NULL,
`termcondition` tinyint(1) NOT NULL DEFAULT '0',
`userstatus` tinyint(4) NOT NULL DEFAULT '0',
`token` varchar(128) NOT NULL,
`dt` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `tb_user`
--
ALTER TABLE `tb_user`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `tb_user`
--
ALTER TABLE `tb_user`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
Demo User: demo@demo.com
Demo Password: demo