PHP Login And Register Form With MySQL

How to Create Login and Register Form in PHP with MySQL Database

PHP Login And Register Form With MySQL Database



In this PHP tutorial we will go step by step on How To Make a Design a Login Form And a Register Form using HTML and CSS and Font-Awesome, and how to connect those two form with mysql database so the user can signup and signin.

What We Will Use To Build This Project ? :
- PHP Programming Language.
- JavaScript Programming Language.
- HTML & CSS.
- Font-Awesome.
- VSCode Editor.
- MySQL Database.
- PhpMyAdmin.







Project Source Code:


------------ Create A Class "db_connect" To Connect Our Form With Database

This file establishes a connection to a MySQL database using PDO (PHP Data Objects). 
It sets up the connection parameters like the server name, username, password, and database name.


<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "register_login_db";

try
{
$conn = new PDO("mysql: host=$servername;dbname=$dbname",$username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{

echo"connection failed: " . $e.getMessage();
die();

}

?>




------------ On The Login Page ------------

This file checks if the user is already logged in. 
If the user is logged in, it redirects them to the index page. 
The page also displays a login form where users can enter their email and password to log in. Additionally, it includes JavaScript to close error messages on the page.

<?php

// check if the user is already logged in , redirect to the index page
session_start();

if(isset($_SESSION['email']))
{
header('Location: index.php');
}


?>

<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<!-- font-awesome link -->
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css"
integrity="sha512-+4zCK9k+qNFUR5X+cKL9EIR+
ZOhtIloNl9GIKS57V1MyNsYpYcUrUeQc9vNfzsWfV28IaLL3i96P9sdNyeRssA=="
crossorigin="anonymous" />
<link rel="stylesheet" href="style.css">
</head>
<body>

<div class="container">

<?php

// display errors

if(isset($_SESSION['error'])){
echo '<div class="alert error"><p>'.$_SESSION['error'].'</p>
<span class="close">&times;</span></div>';
}

unset($_SESSION['error']);

?>


<form action="signin.php" method="post">

<h1>Login</h1>

<div class="input-group">
<label for="email"><i class="fa fa-envelope"></i></label>
<input type="email" name="email" placeholder="Enter Email Address" required>
</div>
<div class="input-group">
<label for="password"><i class="fa fa-lock"></i></label>
<input type="password" name="password" placeholder="Enter Password" required>
</div>

<button type="submit" name="login">login</button>
<p id="goto-page">Don't have an account yet? <a href="registration.php">signup</a></p>

</form>

</div>


<script>

/******* close the error alert ********* */
document.querySelectorAll(".close").forEach(function(closeButton){
closeButton.addEventListener('click', function(){
closeButton.parentElement.style.display = "none";
});

});

</script>


</body>
</html>



------------ The Signin Page ------------

This page processes the login form submission, where it checks if the email exists in the database and verifies the provided password. 
If the email and password match, it sets a session variable for the user and redirects to the index page. In case of an error, such as an incorrect password or email, it sets an error message in the session and redirects the user back to the login page.


<?php

// Include the database connection file
require_once "db_connect.php";

// Check if the login form was submitted
if(isset($_POST['login']))
{
// Start the session
session_start();

// Get the user input from the form
$email = $_POST['email'];
$password = $_POST['password'];

// Check if the email exists in the database
$email_check_query = "SELECT * FROM `user` WHERE `email`=:email";
$stmt = $conn->prepare($email_check_query);
$stmt->bindParam(':email', $email);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);

// If the email exists, verfy the password
if($result)
{
if(password_verify($password, $result['password']))
{
$_SESSION['email'] = $result['email'];
header("Location: index.php");
exit();
}
else
{
$_SESSION['error'] = 'Incorrect Password';
header("Location: login.php");
exit();
}
}

else
{
$_SESSION['error'] = 'Incorrect Email or Password';
header("Location: login.php");
exit();
}
// Clear any existing error messages
unset($_SESSION['error']);

}


// Check if the registration form was submitted
if(isset($_POST['register']))
{
// Start the session
session_start();

// Get the user input from the form
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$hashed_password_ = password_hash($password, PASSWORD_BCRYPT);

// Check if the email already exists in the database
$email_check_query = "SELECT * FROM `user` WHERE `email`=:email";
$stmt = $conn->prepare($email_check_query);
$stmt->bindParam(':email', $email);
$stmt->execute();

// If the email already exists, display an error message and redirect to the registration page
if($stmt->rowCount() > 0)
{
$_SESSION['error'] = 'this email address already exists';
header("Location: registration.php");
exit();
}

/* If the password is less than 8 characters,
display an error message and redirect to the registration page */
if( strlen($password) < 8 )
{
$_SESSION['error'] = 'Password must be at least 8 characters long';
header("Location: registration.php");
exit();
}
// Clear any existing error messages
unset($_SESSION['error']);

// Attempt to insert the user data into the database
try{

$stmt = $conn->prepare("INSERT INTO `user`(`username`, `email`, `password`)
VALUES (:username,:email,:password)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $hashed_password_);
$stmt->execute();
$conn = null;

// Redirect to the login page
header('Location: login.php');

/* If an error occurs during the insert,
display an error message and redirect to the registration page */
}catch(PDOException $ex){

$_SESSION['error'] = 'Unable to register, Please try again later.';
header("Location: registration.php");
unset($_SESSION['error']);
exit();

}

}

?>



------------ The Registration Page ------------

This file first checks if the user is already logged in and, if they are, redirects them to the index page. The page also presents a registration form where users can input their username, email, password, and confirm password. 
Additionally, it incorporates JavaScript to validate password matching and to handle the closure of error messages on the page.


<?php

// if the user is already logged in , redirect to the index page
session_start();

if(isset($_SESSION['email']))
{
header('Location: index.php');
}


?>

<!DOCTYPE html>
<html>
<head>
<title>Registration</title>
<!-- font-awesome link -->
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css"
integrity="sha512-+4zCK9k+qNFUR5X+cKL9EIR+
ZOhtIloNl9GIKS57V1MyNsYpYcUrUeQc9vNfzsWfV28IaLL3i96P9sdNyeRssA==" crossorigin="anonymous" />
<link rel="stylesheet" href="style.css">
</head>
<body>

<div class="container">



<?php
// display errors
//session_start();
if(isset($_SESSION['error'])){
echo '<div class="alert error"><p>'.$_SESSION['error'].'</p>
<span class="close">&times;</span></div>';
}

unset($_SESSION['error']);

?>


<form action="register.php" method="post">

<h1>Register</h1>
<div class="input-group">
<label for="username"><i class="fa fa-user"></i></label>
<input type="text" name="username" placeholder="Enter Username" required>
</div>
<div class="input-group">
<label for="email"><i class="fa fa-envelope"></i></label>
<input type="email" name="email" placeholder="Enter Email Address" required>
</div>
<div class="input-group">
<label for="password"><i class="fa fa-lock"></i></label>
<input type="password" name="password" id="password" placeholder="Enter Password" required>
</div>
<div class="input-group">
<label for="confirm_password"><i class="fa fa-lock"></i></label>
<input type="password" name="confirm_password" id="confirm_password"
placeholder="Confirm Password" required>
</div>
<span id="password-error"></span>
<button type="submit" name="register" id="register-button" disabled>Register</button>
<p id="goto-page">Already have an account? <a href="login.php">login</a></p>
</form>

</div>


<script>

const passwordInput = document.getElementById('password');
const confirmPasswordInput = document.getElementById('confirm_password');
const passwordError = document.getElementById('password-error');
const registerButton = document.getElementById('register-button');

// Listen for changes to the confirm password input field
confirm_password.addEventListener("keyup", function(){

// Check if the password and confirm password fields match
if(passwordInput.value !== confirmPasswordInput.value)
{
// If the passwords do not match, display an error message and disable the register button
passwordError.innerHTML = "Passwords do not match";
registerButton.disabled = true;
}
else
{
// If the passwords match, clear the error message and enable the register button
passwordError.innerHTML = "";
registerButton.disabled = false;
}

});


/******* close the error alert ********* */
document.querySelectorAll(".close").forEach(function(closeButton){
closeButton.addEventListener('click', function(){
closeButton.parentElement.style.display = "none";
});

});



</script>




</body>
</html>




------------ The Register Page ------------

This file handles the registration form submission by first verifying if the provided email exists in the database and ensuring that the password is at least 8 characters long. 
If the email is not already registered, and the password meets the criteria, it proceeds to insert the user's data into the database and then redirects them to the login page. 
In case of any registration errors, such as an existing email, the script sets an error message in the session and redirects the user back to the registration page.

<?php

// Include the database connection file
require_once "db_connect.php";

// Check if the registration form was submitted
if(isset($_POST['register']))
{
// Start the session
session_start();

// Get the user input from the form
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$hashed_password_ = password_hash($password, PASSWORD_BCRYPT);

// Check if the email already exists in the database
$email_check_query = "SELECT * FROM `user` WHERE `email`=:email";
$stmt = $conn->prepare($email_check_query);
$stmt->bindParam(':email', $email);
$stmt->execute();

// If the email already exists, display an error message and redirect to the registration page
if($stmt->rowCount() > 0)
{
$_SESSION['error'] = 'this email address already exists';
header("Location: registration.php");
exit();
}

/* If the password is less than 8 characters,
display an error message and redirect to the registration page */
if( strlen($password) < 8 )
{
$_SESSION['error'] = 'Password must be at least 8 characters long';
header("Location: registration.php");
exit();
}
// Clear any existing error messages
unset($_SESSION['error']);

// Attempt to insert the user data into the database
try{

$stmt = $conn->prepare("INSERT INTO `user`(`username`, `email`, `password`)
VALUES (:username,:email,:password)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $hashed_password_);
$stmt->execute();
$conn = null;

// Redirect to the login page
header('Location: login.php');

/* If an error occurs during the insert,
display an error message and redirect to the registration page */
}catch(PDOException $ex){

$_SESSION['error'] = 'Unable to register, Please try again later.';
header("Location: registration.php");
unset($_SESSION['error']);
exit();

}

}

?>



------------ The Index Page ------------

This page checks if the user is logged in; if not, it redirects them to the login page. 
It primarily serves as a basic placeholder for the index page, with no content.


<?php

// check if the user is already logged in , redirect to the login page

session_start();

if(isset($_SESSION['email']))
{
$email = $_SESSION['email'];
}
else{
header('Location: login.php');
}

?>

<!DOCTYPE html>
<html>
<head>
<title>Registration</title>
<!-- font-awesome link -->
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css"
integrity="sha512-+4zCK9k+qNFUR5X+cKL9EIR+
ZOhtIloNl9GIKS57V1MyNsYpYcUrUeQc9vNfzsWfV28IaLL3i96P9sdNyeRssA=="
crossorigin="anonymous" />
<link rel="stylesheet" href="style.css">
</head>
<body>

<div class="container">
<h1>Index</h1>
</div>

</body>
</html>



------------ The Logout Page ------------

This file logs the user out by destroying their session, unsetting the email session variable, and then redirects the user to the login page.


<?php

// logout script
session_start();
unset($_SESSION['email']);
session_destroy();
header('Location: login.php');

?>



                                          


////// OUTPUT : 


PHP Register Form With MySQL Database

PHP Register Form With MySQL Database 2

PHP Register Form With MySQL Database - Password Error

PHP Register Form With MySQL Database - Email Error


PHP Login Form With MySQL Database

PHP Login Form With MySQL Database - Error


if you want the source code click on the download button below

download the source code









Share this

Related Posts

Previous
Next Post »