Login form using PHP & MYSQL | Simple Signin System


Simple Login Form in PHP

The login system plays a critical role in almost every dynamic website. Whenever you need to secure user information or restrict access, you must implement a login form. To create a simple login system in PHP, you need an HTML form for the front-end and a PHP script for the back-end to authenticate the user.

For example, if you sell products on your website, you might want users to log in first before they can purchase anything. Through a login form, we can secure sensitive information and personal dashboards.

Every modern website uses a SignIn and SignUp system. The SignUp system is used to collect data from users and create their profiles, while the Login (SignIn) system authenticates that data to allow access.

We create this system to restrict unknown users. The user must first log in using authenticated credentials to access secured information.

Login System Using PHP & MySQL

MySQL plays a huge role alongside PHP in creating a login system. When a user enters their username (or email) and password in the HTML form, PHP runs a MySQL query to verify the details.

The MySQL query checks if the entered credentials match the records stored in the database. If the information matches, the user is successfully logged in.

If an unknown user tries to log in with incorrect details, the information will not match the database records, and the login attempt will fail. This restricts unauthorized access.

For a PHP login system, we use the MySQL SELECT query. With the help of the SELECT query, we fetch the database row that corresponds to the user's username or email, and then we verify the password.

User Authentication Process

The user authentication process is the core of any login system. Authentication is the process of verifying the information provided by the user during the login attempt against the data saved during registration.

Authentication Process Steps:

1. First, the user enters their authenticated information (such as username/email and password) into the HTML form.
2. After submission, the PHP script checks the database. If the username exists and the password matches, the user is logged in.
3. If the credentials do not match, the login fails, and an error message is displayed.
4. This authentication process strictly restricts unknown users from accessing secure areas without valid credentials.

Step 1: Create a MySQL Database Table

To create a login form, you first need a MySQL database table. Users can only be authenticated if their information exists in the database. Let's create a users table. Notice that we use an AUTO_INCREMENT ID as the primary key.


CREATE TABLE `users` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `uname` VARCHAR(50) NOT NULL,
  `upassword` VARCHAR(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Step 2: Insert Data into the MySQL Database Table

A user cannot log in unless their data exists in the table. Let's insert sample data into the table. In a real-world scenario, the password should be hashed using PHP's password_hash() function during the SignUp process. For testing purposes, let's insert a hashed password.


-- The password here is 'admin@123' hashed using PHP password_hash()
INSERT INTO `users` (`uname`, `upassword`) VALUES ('admin', '$2y$10$YourHashedPasswordStringHere');

Step 3: Create a Database Configuration File

We need a config.php file to securely connect PHP and MySQL using PDO (PHP Data Objects). To create a config file, you must define the following details:

Database Host

The address of the server. For a local server, use localhost or 127.0.0.1.

Database Name

The name of the database you created.

Database Username

The username of the MySQL server (default is root for localhost).

Database Password

The database password (default is empty for localhost).

Create a file named config.php and add the following secure PDO connection code:

<?php
// config.php
$databaseHost = '127.0.0.1'; // or localhost
$databaseName = 'test';      // Your database name
$databaseUsername = 'root';  
$databasePassword = '';      

try {
    // Create a PDO connection
    $pdo = new PDO("mysql:host=$databaseHost;dbname=$databaseName;charset=utf8mb4", $databaseUsername, $databasePassword);
    // Set PDO error mode to exception
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Database Connection Failed: " . $e->getMessage());
}
?>

Step 4: Make an HTML Login Form

We need an HTML form where the user can enter their credentials. This simple login form contains two input fields (Username and Password) and a submit button. We use the POST method to submit data securely.

HTML Form Code (login.php)

<html>
<head>
    <title>Login Form</title>
</head>
<body>
<center>
    <form action="login.php" method="POST">
        <h3>User Login</h3>
        
        <b>Username:</b><br/>
        <input type="text" name="uname" required><br><br>

        <b>Password:</b><br/>
        <input type="password" name="upassword" required><br><br>

        <input type="submit" name="login" value="Login">
    </form>
</center>
</body>
</html

 

Design the Login Form Using CSS

Along with PHP programming, the design should be clean. Here is simple CSS to make the input boxes and button look attractive. Add this inside your HTML <head> section.


<style type="text/css">
input[type=text], input[type=password] {
  width: 250px;
  padding: 10px 15px;
  margin: 5px 0;
  border: 1px solid #ccc;
  border-radius: 4px;
}
input[type=submit] {
  width: 120px;
  padding: 10px 20px;
  border: none;
  background-color: green;
  color: white;
  font-size: 16px;
  cursor: pointer;
  border-radius: 4px;
}
input[type=submit]:hover {
  background-color: darkgreen;
}
</style>

It produces the following output:

Login form in PHP. Create a Login system in PHP, Design HTML form for SIGN IN

Step 5: Create the PHP Script for Login

In this step, we write the PHP logic to authenticate the user. When the user clicks the login button, the PHP script securely connects to the MySQL server and processes the data.

We use a PDO Prepared Statement to prevent SQL Injection. The script fetches the user's hashed password from the database and uses the password_verify() function to securely check if the entered password matches.

PHP Login Script

<?php 
// Include the database connection file
require_once("config.php");

// Start the session to store user login status
session_start();

if(isset($_POST['login'])) {
    // Get and trim form data
    $uname = trim($_POST['uname']);
    $upassword = $_POST['upassword'];

    try {
        // Securely select user data using a PDO Prepared Statement
        $sql = "SELECT id, uname, upassword FROM users WHERE uname = :uname";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([':uname' => $uname]);
        
        // Fetch the user record
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        // Check if user exists AND if the password matches using password_verify()
        if($user && password_verify($upassword, $user['upassword'])) {
            // Password is correct, create a session
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['uname'];
            
            echo "<span style='color:green;'>You have logged in successfully!</span>";
            // header("Location: dashboard.php"); // Redirect to secure page
            // exit();
        } else {
            echo "<span style='color:red;'>Invalid Username or Password.</span>";
        }
    } catch(PDOException $e) {
        die("Error: " . $e->getMessage());
    }
}
?>

Why We Use the POST Method in Login Forms

As discussed in a previous tutorial about the POST method in PHP, the POST method sends form data directly within the HTTP request body. It does not show the submitted values in the page URL.

Because login forms contain highly sensitive information (like passwords), using the POST method is strictly required to secure the data from anyone looking at the browser or network logs.

Why You Should NEVER Use the GET Method in a Login System

The GET method appends the submitted form values directly to the URL, separated by a ? (question mark).

If you use the GET method for a login form, the user's password will be clearly visible in the URL bar, like this:
http://example.com/login.php?uname=admin&upassword=MySecretPassword

This completely compromises security because the password gets saved in the browser history, server logs, and can be seen by anyone looking at the screen. Therefore, you must never use the GET method for login or registration systems.


Please Share

Recommended Posts:-

Previous Posts:-

Featured Items:-


Universal ID Card Management System in PHP MySQL

$79



Result management system with Marksheet in PHP website | PHP Scripts

$39



Paypal Payment form in PHP website with MYSQL database | International Payments

$12





2 Comments
Mujtaba 12 Dec 2022
$res = mysqli_query($mysqli,"select* from user where uname='$uname'and upassword='$upassword'");

$result=mysqli_fetch_array($res); if($result) { echo "You are login Successfully ";

This code will always evaluated to true, becuase $result is 1.

@Mujtaba replied by Techno Smarter 13 Dec 2022

We have updated our code. You can check again or we have created a new tutorial for registration and login system in PHP. You check it with hash passwords and validations with bootstrap.