Step-by-Step PHP Login Form Tutorial

Faraz Logo

By Faraz -

Learn to build a secure MySQL PHP login form step by step. Enhance your web security with this beginner-friendly PHP login system tutorial.


Step-by-Step PHP Login Form Tutorial.jpg

In the world of web development, creating a login form is a fundamental step towards building secure and user-friendly websites. PHP, a versatile server-side scripting language, and XAMPP, a popular web development environment, make an excellent combination for crafting a robust login system. In this tutorial, we will guide you through the process of creating a PHP login form using XAMPP, step by step. Whether you're a beginner or an experienced developer looking to refresh your skills, this guide will help you build a secure and efficient login system.

Table of Contents

  1. Prerequisites
  2. Creating the Database
  3. Setting Up the PHP Files
  4. Writing the PHP Code
  5. Conclusion
  6. FAQs

Prerequisites

Before we dive into the tutorial, let's ensure you have everything set up:

1. Install XAMPP

If you haven't already, download and install XAMPP from the official website (https://www.apachefriends.org/index.html). XAMPP provides you with Apache, MySQL, PHP, and Perl, creating a local web server environment on your computer.

2. Basic HTML and PHP Knowledge

This tutorial assumes you have a basic understanding of HTML and PHP. If you're new to these languages, consider brushing up on the basics through online resources or tutorials.

Creating the Database

The first step in building our PHP login form is to set up the database. Follow these steps:

1. Start XAMPP

Launch XAMPP control panel and start the Apache and MySQL modules.

step by step guide connecting php to mysql database with xampp

2. Access phpMyAdmin

Open your web browser and navigate to http://localhost/phpmyadmin/. Here, you can manage your MySQL databases.

step by step guide connecting php to mysql database with xampp

3. Create a Database

Click on "Databases" in the top menu and create a new database. Give it a meaningful name; for example, "login_system."

4. Create a User Table

Inside your new database, create a table named "users" with the following columns:

  • id (Auto-increment)
  • name (Varchar)
  • username (Varchar)
  • password (Varchar)
Step-by-Step PHP Login Form Tutorial Create Database

Setting Up the PHP Files

Now that we have our database in place, it's time to create the PHP files for our login system:

1. Create a Folder

Inside the "htdocs" folder of your XAMPP installation, create a new folder for your project, such as "login_system."

2. Create PHP Files

Inside your project folder, create the following PHP files:

Writing the PHP Code

We'll now start writing the PHP code for each file, as follows:

1. config.php

This file contains configuration settings and connects the web application to the database. It stores important information like database credentials, site URLs, and other global settings used throughout the application.

<?php

$server = "localhost";
$username = "root";
$pass = "";
$database = "mydata";

$conn = mysqli_connect($server, $username, $pass, $database);

if (!$conn) {
   die("<script>alert('Connection Failed.')</script>");
}
?>

2. login.php

This file handles the login process. It contains a login form where users can enter their credentials (e.g., username and password). When the user submits the form, this script verifies the credentials against the database and, if valid, allows access to the index.php page.

<?php

include 'config.php';

if (isset($_POST['submit'])) {
    $email = $_POST['email'];
    $password = $_POST['password'];

    $sql = "SELECT * FROM userdetails where UserName = '$email' AND Password = '$password'";
    $result = mysqli_query($conn, $sql);

    if (mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
        session_start();
        $_SESSION['Login'] = true;
        $_SESSION['username'] = $row['Name'];
        header("Location: index.php");
    } else {
        echo "<script>alert(' Email or Password is wrong. ')</script>";
    }
}
?>

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        .center {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

        input {
            width: 80%;
            padding: 10px;
            margin-bottom: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        input[type='Submit'] {
            cursor: pointer;
            width: 50%;
            text-align: center;
        }
    </style>
    <title>Login Form</title>
</head>

<body>
    <div class="center">
        <h1>Login</h1>
        <form action="" method="POST">
            <input type="email" name="email" placeholder="Email" required>
            <input type="password" name="password" placeholder="Password" required>
            <input name="submit" type="Submit" value="Login">
            <div class="signup_link">
                Not a Member ? <a href="signup.php">Signup</a>
            </div>
        </form>
    </div>
</body>

</html>
Login Form

3. index.php

The index.php file serves as the main entry point of the web application. It displays the homepage for users.

<?php

include "config.php";

session_start();

$sql = "SELECT * FROM userdetails where Name = '$_SESSION[username]'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    if (!isset($_SESSION["Login"]) && $_SESSION["Login"] == false) {
        header("Location: login.php");
    }
} 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">
    <title>Welcome <?php echo "$_SESSION[username]"; ?> </title>
    <style>
        .logoutBtn {
            padding: 10px 20px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
        }

        .logoutBtn:hover {
            background-color: #0056b3;
        }
    </style>
</head>

<body>
    <h1>Welcome <?php echo "$_SESSION[username]"; ?></h1>
    <a class="logoutBtn" href="logout.php">Logout</a>
</body>

</html>
Index Page

4. logout.php

The logout.php file is responsible for logging users out of the application. When a user clicks the logout button, this script clears their session or authentication tokens, effectively ending their current session and redirecting them to a logged-out state.

<?php

include 'config.php';

session_start();

session_unset();
session_destroy();
header("Location: login.php");

?>

Run the PHP Script

  1. Move the PHP script to your XAMPP "htdocs" folder (usually located in "C:\xampp\htdocs" on Windows)
  2. Open your web browser and navigate to http://localhost/your_script_name.php. For ex: http://localhost/login.php.
  3. If the connection was successful, you should see the message "Connected successfully"

Conclusion

Congratulations! You've successfully created a PHP login form using XAMPP. This essential skill will serve you well as you continue to develop web applications and websites. Feel free to enhance your login system with additional features like password hashing and user profile management.

Now, you're ready to build secure and user-friendly login systems for your web projects. Happy coding!

FAQs

1. Why use XAMPP for web development?

XAMPP provides an all-in-one package that simplifies the setup of a local web server environment, including Apache, MySQL, PHP, and Perl, making it ideal for web development.

2. Is PHP secure for user authentication?

PHP can be secure for user authentication when implemented correctly, including measures like password hashing and input validation.

3. How can I improve the security of my login system?

To enhance security, consider using techniques like password hashing, input validation, and implementing a two-factor authentication (2FA) system.

4. Can I use this login system for commercial projects?

Yes, you can use this login system as a foundation for commercial web projects.

That’s a wrap!

Thank you for taking the time to read this article! I hope you found it informative and enjoyable. If you did, please consider sharing it with your friends and followers. Your support helps me continue creating content like this.

Stay updated with our latest content by signing up for our email newsletter! Be the first to know about new articles and exciting updates directly in your inbox. Don't miss out—subscribe today!

If you'd like to support my work directly, you can buy me a coffee . Your generosity is greatly appreciated and helps me keep bringing you high-quality articles.

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post