Tuesday, April 2, 2019

how to make a login form in php and mysql with js validation.

Simple 6 step

Step 1: Create login form in html

//LoginForm.php

<!DOCTYPE HTML>
<html>
<head>
<title>LoginForm.php</title>
<!-- Using external stylesheet to make the registration form look attractive -->
<link rel = "stylesheet" type = "text/css" href="Style.css"/>

 
<!-- Javascript validation for user inputs -->
<script type="text/javascript">

function validate()
{
var username = document.login.username.value;
var password = document.login.password.value;

if (username==null || username=="")
{
  alert("Username can't be blank");
  return false;
}
else if (password==null || password=="")
{
  alert("password can't be blank");
  return false;
}
}
</script>
</head>

<body>

<!-- Make a note that the method type used is post, action page is Login.php and validate() function will get called on submit -->
<div style="text-align:center"><h1>PHP Login Form using MySQL</h1></div>
<br>
<form name="login" method="post" action="Login.php" onsubmit="return validate();" >
<div>Username: <input type="text" name="username" /> </div>
<div>Password: <input type="password" name="password" /> </div>
<div><input type="submit" value="Login"></input> <input type="reset" value="Reset"></input></div>
</form>
</body>
</html>

Step 2: Create database connection file

//DBConnection.php

//This code is used to establish a connection with the MySQL database server
<?php
define('DB_SERVER', 'localhost:3306'); //database server url and port
define('DB_USERNAME', 'root');  //database server username
define('DB_PASSWORD', 'root123'); //database server password
define('DB_DATABASE', 'profile'); //where profile is the database

$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>


Step 3: Create login.php form in html

//Login.php


<!DOCTYPE HTML>
<html>
<body>
<?php
include_once("DBConnection.php");
session_start(); //always start a session in the beginning
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (empty($_POST['username']) || empty($_POST['password'])) //Validating inputs using PHP code
{
echo
"Incorrect username or password"; //
header("location: LoginForm.php");//You will be sent to Login.php for re-login
}

$inUsername = $_POST["username"]; // as the method type in the form is "post" we are using $_POST otherwise it would be $_GET[]
$inPassword = $_POST["password"];
$stmt= $db->prepare("SELECT USERNAME, PASSWORD FROM PROFILE WHERE USERNAME = ?"); //Fetching all the records with input credentials
$stmt->bind_param("s", $inUsername); //bind_param() - Binds variables to a prepared statement as parameters. "s" indicates the type of the parameter.
$stmt->execute();
$stmt->bind_result($UsernameDB, $PasswordDB); // Binding i.e. mapping database results to new variables
  
//Compare if the database has username and password entered by the user. Password has to be decrypted while comparing.
if ($stmt->fetch() && password_verify($inPassword, $PasswordDB))
{
$_SESSION['username']=$inUsername; //Storing the username value in session variable so that it can be retrieved on other pages
header("location: UserProfile.php"); // user will be taken to profile page
}
else
{
   echo "Incorrect username or password";
  ?>

  <a href="LoginForm.php">Login</a>
       <?php
}
}
       ?>
</body>
</html>

Step 4: Create User profile page

//UserProfile.php

<html>
<title>userProfile.php</title>
<body>
<?php
session_start();
$username = $_SESSION['username']; //retrieve the session variable
?>

<div style="text-align:center"><h1>User Profile</h1></div>
<br/>

<div style="font-weight:bold"> Welcome <?php echo $username ?> </div>
  
<div style="text-align: right"><a href="Logout.php">Logout</a></div> <!-- calling Logout.php to destroy the session -->

<?php
if(!isset($_SESSION['username'])) //If user is not logged in then he cannot access the profile page
{
//echo 'You are not logged in. <a href="login.php">Click here</a> to log in.';
header("location:LoginForm.php");
}
?>
</body>
</html>


Step 5: Create logout file

/Logout.php

<?php

session_start();
$username = $_SESSION['username']; //retrieve the session variable

unset($_SESSION['username']); //to remove session variable
session_destroy(); //destroy the session
header("location: LoginForm.php"); //to redirect back to "Login.php" after logging out
exit();

if(!isset($_SESSION['username'])) //If user is not logged in then he cannot access the profile page
{
//echo 'You are not logged in. <a href="login.php">Click here</a> to log in.';
header("location:LoginForm.php");
}
?>

Step 5: Create css file
//Style.css

/* Sample CSS - Modify it as per your taste */
input[type=text], input[type=password] {
background-color: #EEEEEE;
border: none;
color: black;
width:auto;
padding: 8px 52px;
text-decoration: none;
margin: 4px 2px;
cursor: pointer;
}

input[type=button], input[type=submit], input[type=reset] {
background-color: #4CAF50;
border: none;
color: white;
padding: 16px 32px;
text-decoration: none;
margin: 4px 2px;
cursor: pointer;
}

body{
text-align:right;
margin: 50px 400px;
}