PHP - Login Form With MySQL DataBase

How To Make Login Form In PHP With MySQL DataBase

Login Form In PHP With MySQL DataBase


In this PHP tutorial we will see how to create a login Page with a mysql database.

This page will contains a simple login form Using HTML, CSS and JavaScript.
the user enter his email and password and click on the login button,
and all we have to do is to check if a user with this email and password already exists on the database, and if the user don't exists show an error message, else redirect to the index page.

to do that we will ceate a class (db_connect) to connect our login form with mysql database, and After a successful login,redirect the user to the home page (index.php).
plus we will create a logout page system.






Project Source Code:


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


<?php

// Define database connection parameters
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "login_db";

try
{
    // Create a new PDO instance
  $conn = new PDO("mysql: host=$servername;dbname=$dbname", $username, $password);
  // Set PDO error mode to exception
  $conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
  // If a connection error occurs, display it
  echo"connection failed: " . $e->getMessage();
}

?> 



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


<?php 

session_start();

$email = "";
$username = "";

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

?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css"/>
  <title>Index</title>

<style>

*{ margin:0; padding:0; box-sizing:border-box; font-family:Arial, sans-serif; }

body{ background-color:#f7f7f7; }

h1{ font-size:72px; font-weight:700; text-transform:uppercase; 
    color:#555; margin-top:50px ; text-align:center;}


</style>


</head>

<body>

<h1>Welcome Back: <?php echo $username; ?> <a href="logout.php">logout</a> </h1>

</body>
</html>




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


    <?php

// Include database connection file
require_once 'db_connect.php';

// Initialize error message variable
$error_msg = "";

// Check if the login form is submitted
if(isset($_POST['submit']))
{
    // Get user input values
    $email = $_POST['email'];
    $password = $_POST['password'];

    /*
    user 1 = user11@email.com - pass123@@
    user 2 = admin@admin.com - admin356@aa#
    user 3 = test@example.com - testpass789##
    */

    // Prepare and execute database query to fetch user data by email
    $stmt = $conn -> prepare('SELECT * FROM `user` WHERE email = :email');
    $stmt->bindParam(':email', $email);
    $stmt->execute();

    // Fetch user data as an associative array
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    // If user exists, verify password and set session variables
    if($result)
    {
        if(password_verify($password, $result['password'])){
            
            // Start a new session
            session_start();

            // Set session variables
            $_SESSION['email'] = $result['email'];
            $_SESSION['username'] = $result['username'];

            // Redirect user to the home page
            header('Location: index.php');

        }
        else
        {
            // If password is incorrect, set error message
          $error_msg = "Invalid Email Or Password";
        }
    }
    else
    {
        // If user doesn't exist, set error message
      $error_msg = "Invalid Email Or Password";
    }
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css"/>
  <title>Login Form</title>

<style>

*{ margin:0; padding:0; box-sizing:border-box; font-family:Arial, sans-serif; }

body{ background-color:#f7f7f7; }

.login-form{ width:400px; margin:50px auto; background-color:#fff; 
             box-shadow:0px 2px 10px rgba(0,0,0,0.1); padding:40px; border-radius:10px;
             display:flex; flex-direction:column; align-items:center; }

h1{ font-size:36px; font-weight:700; text-transform:uppercase; color:#555; margin-bottom:30px; }

.input-container{ width:100%; margin-bottom:20px; position:relative; }

.input-container i{ position:absolute; left:10px; top:50%; color:#aaa; font-size:20px;
                    transform: translateY(-50%); }

input{ width:100%; height:50px; padding:10px 40px; font-size: 16px; border:none;
       border-radius:25px; background-color:#f7f7f7; color:#555; }

button{ width:100%; height:50px; margin-top:20px; border:none; border-radius:25px; 
        background-color:#555; color:#fff; font-size:16px; font-weight:700; 
        text-transform:uppercase; cursor:pointer; transition: background-color 0.3s ease-in-out; }

button:hover{ background-color:#444; }

</style>


</head>

<body>

<form action="#" method="post" class="login-form">

<h1>Login</h1>
<div class="input-container">
    <i class="fa fa-envelope"></i>
    <input type="email" name="email" placeholder="email" required>
</div>
<div class="input-container">
    <i class="fa fa-lock"></i>
    <input type="password" name="password" placeholder="password" required>
</div>

<button type="submit" name="submit">login</button>

<?php echo '<p style="color:red; margin-top:10px">'.$error_msg.'</p>'; ?>

</form>

</body>
</html>
                                                     

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


<?php 

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

?>

                                          


////// OUTPUT : 


PHP Login Page With MySQL Database


PHP Login Page With MySQL Database - Error

Index Page




download the source code








Share this

Related Posts

Previous
Next Post »