Skip to main content
Login Form PHP MySQL With Session

Login Form PHP MySQL With Session

If the website we create differentiates users based on their access, such as admin and guest, a PHP login form with a session is essential.

We can limit user access rights with the login form so that they can access content or menus based on their role.

So, how do you make a PHP and MySQL login form that uses session? Let’s get right to the instructions for making it.

PHP Login Form Tutorial

Several things must be prepared before creating a PHP login form with a session, namely:

  • Web Server. PHP files cannot be executed in the absence of a web server. There are numerous web server applications available. In this tutorial, however, we will use XAMPP as a web server.
  • Text Editor. We will use the Visual Studio Code text editor to write program code.
  • Web Browser. Used to access a website that has been created later. You are free to use any web browser you want. In this tutorial, I’ll be using Google Chrome.

If the above tool is ready, we can proceed to the next 9 steps to create the following php login form:

1. Run XAMPP

XAMPP is a cross-platform (Windows, Linux, and macOS) application that is used to set up a local web server on our computer.

We can use this application to develop and test websites on a local computer. However, we must first install XAMPP on our computer. Read more about How to Install XAMPP on Windows (Easiest!).

We launch the application after it has been installed. Then, click the Start button to start the Apache and MySQL servers.

XAMPP Control Panel
xampp control panel

2. Create Database

A database is required to store user data such as username, password, and name. To create a database, open phpMyAdmin in a web browser by going to http://localhost/phpmyadmin/.

Click New on the left side of the page to create a new database. Then, in the provided column, enter the name of the database to be created. We will create a database called sribuhost_login in this tutorial. Then click the Create button.

New Database Page in phpMyAdmin
new database page in phpmyadmin

We create a users table after successfully creating the database, which will later be used to store user data. To create a users table, enter the SQL code below into the SQL menu in phpMyAdmin:

CREATE TABLE `users` (
    `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `username` varchar(255) NOT NULL UNIQUE KEY,
    `password` varchar(255) NOT NULL,
    `name` varchar(255) NOT NULL
);

INSERT INTO `users` (`id`, `username`, `password`, `name`) VALUES
(1, 'sribuhost', 'pass123', 'Sribuhost');

To run the SQL code above, click the Go button, as shown below:

SQL Menu in phpMyAdmin
sql menu in phpmyadmin

We have now successfully created a users table with one user’s data.

Table Page in phpMyAdmin
table page in phpmyadmin

Related post: How to Import MySQL Database in phpMyAdmin Easily


3. Creating a Project Structure

We’ll write the PHP login form program code after we’ve created the database and user data. But first, we must create the structure of our web project.

First, we make a special folder in which to save our website. The folder must be placed in the htdocs folder, which is the web server’s home folder. The htdocs folder is located by default at C:\xampp\htdocs.

Web Folder in htdocs
web folder in htdocs

In this tutorial, we will create a web folder called sribuhost_login. Then, in Visual Studio Code, open the folder. Within this folder, we create the following files with .php and .css extensions:

Opened Folder in Visual Studio Code
opened folder in visual studio code

The next step will explain what these files are.

4. Create a Login Page (index.php)

The code for the login page is contained in the index.php file. Some PHP code can be found at the top of this file. If the user has previously logged in, this code is used to redirect them to the home page (home.php).

<?php

session_start();

if (isset($_SESSION["name"])) {
    header("location: ./home.php");
    exit();
}

?>

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

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Login Form PHP MySQL With Session - Sribuhost</title>

    <link rel="stylesheet" href="./style.css" />
</head>

<body>
    <div class="container">
        <div class="box">
            <h1 class="box__title">Sribuhost</h1>
            <p class="box__subtitle">Please log in to continue</p>
            <?php if (isset($_SESSION["login_failed"])): ?>
                <div class="alert">
                    Incorrect username or password!
                </div>
            <?php unset($_SESSION["login_failed"]);endif; ?>
            <form action="./auth.php" method="post" class="form">
                <input type="text" class="form__input" placeholder="Username" name="username" required />
                <input type="password" class="form__input" placeholder="Password" name="password" required />
                <button class="form__button" type="submit" name="submit">LOGIN</button>
            </form>
        </div>
    </div>
</body>

</html>

5. Creating a Home Page (home.php)

We create another page, home.php, to see if the login session was successfully created. This page is only accessible to users who have previously logged in.

There is some PHP code in this file that is used to redirect users to the login page (index.php) if they have not yet logged in.

<?php

session_start();

if (!isset($_SESSION['name'])) {
    header('location: ./index.php');
    exit;
}

?>

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

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Login Form PHP MySQL With Session - Sribuhost</title>

    <link rel="stylesheet" href="./style.css" />
</head>

<body>
    <div class="container">
        <div class="information">
            <h1 class="information__title">You are logged in as <?= $_SESSION['name'] ?></h1>
            <a href="./logout.php" class="information__button">Logout</a>
        </div>
    </div>
</body>

</html>

6. Create User Authentication Function (auth.php)

The auth.php file is used to authenticate log-in users. This file contains only PHP code that validates the user’s username and password.

If the validation is successful, a new session is created as evidence that the user has successfully logged in.

<?php

session_start();

if (isset($_SESSION['name'])) {
    header('location: ./home.php');
    exit;
}

if (!isset($_POST['submit'])) {
    header('location: ./index.php');
    exit;
}

$conn = mysqli_connect('localhost', 'root', '', 'sribuhost_login');
$username = $_POST['username'];
$password = $_POST['password'];

$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";

$result = mysqli_query($conn, $query);
$users_num = mysqli_num_rows($result);

if ($users_num < 1) {
    $_SESSION['login_failed'] = true;
    header('location: ./index.php');
    exit;
}

$user = mysqli_fetch_assoc($result);
$_SESSION['name'] = $user['name'];

header('location: ./home.php');
exit;

7. Create a Logout Function (logout.php)

When the logout button on the home page (home.php) is clicked, the code in the logout.php file is executed. This code deletes all user sessions and redirects the user to the login page (index.php).

<?php

session_start();
session_destroy();

header('location: ./index.php');
exit;

8. Adding Style to the Page (style.css)

Here we will add some styling to the website to improve its appearance. The style code is placed in the style.css file, which is then accessed through the login (index.php) and home (home.php) pages.

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@400;700&display=swap");

html {
    font-family: "Poppins", sans-serif;
    font-size: 14px;
}

body {
    background-image: linear-gradient(to bottom right, #86be67, #7fba5c);
    color: #444;
    margin: 0;
    min-height: 100vh;
    padding: 0;
}

.container {
    padding: 6rem 0;
}

.box {
    background-color: #fff;
    box-shadow: 0 0 0.5rem rgba(68, 68, 68, 0.5);
    margin: 0 auto;
    padding: 4rem 2rem;
    text-align: center;
    width: 25%;
}

.box__title {
    margin: 0 0 0.25rem;
}

.box__subtitle {
    color: #888;
    margin: 0 0 2rem;
}

.form {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.form__input {
    background-color: #eee;
    border: none;
    color: inherit;
    font-family: inherit;
    font-size: 1rem;
    padding: 0.75rem 1.25rem;
}

.form__input::placeholder {
    color: #888;
}

.form__button {
    background-color: #55ae50;
    border: none;
    color: #fff;
    cursor: pointer;
    font-family: inherit;
    font-size: 1rem;
    margin-top: 1rem;
    padding: 0.75rem 2rem;
    transition: all 0.15s;
}

.form__button:hover {
    background-color: rgba(85, 174, 80, 0.875);
}

.information {
    color: #fff;
    text-align: center;
}

.information__title {
    margin: 0 0 2rem;
}

.information__button {
    background-color: #ae5050;
    border: none;
    color: #fff;
    cursor: pointer;
    font-family: inherit;
    font-size: 1rem;
    margin-top: 1rem;
    padding: 0.75rem 2rem;
    text-decoration: none;
    transition: all 0.15s;
}

.information__button:hover {
    background-color: rgba(174, 80, 80, 0.875);
}

.alert {
    background-color: #ae5050;
    color: #fff;
    margin-bottom: 2rem;
    padding: 0.75rem 2rem;
}

9. Running PHP Login Form in Web Browser

After all of the necessary files have been created, it is time to run the file. To use it, launch a web browser and navigate to the address http://localhost/sribuhost_login/.

The login page is the first page that appears. Enter the username and password as they appear in the database (username: sribuhost, password: pass123).

Login Page
login page

If we successfully login, we will be redirected to the home page (home.php), as shown below:

Home Page
home page

Conclusion

This is a PHP tutorial on how to create a login form. If the website does not load, check that the web folder created is in htdocs.

We can change the appearance of the website by editing the style.css file. If no changes have been made after changing the style.css file, try refreshing the page or using another web browser.

Here’s a tutorial for creating PHP and MySQL login forms with session. This tutorial’s source code is available in the Sribuhost github repository here. I hope everyone finds this article useful.

Share this

Shafy Gunawan

I’m a web developer. I spend my whole day, practically every day, experimenting with HTML, CSS, JavaScript, and PHP; dabbling with Python programming language; and share the knowledge that I learned.

7 thoughts to “Login Form PHP MySQL With Session”

  1. Hello! I could have sworn I’ve been to this blog before but after reading through some of the post I realized it’s new to me. Anyways, I’m definitely glad I found it and I’ll be book-marking and checking back often!

  2. You completed several nice points there. I did a search on the matter and found mainly persons will agree with your blog.

  3. Hi I am so delighted I found your site, I really found you by error, while I was searching on Digg for something else, Anyhow I am here now and would just like to say thanks for a remarkable post and a all round thrilling blog (I also love the theme/design), I don抰 have time to read it all at the moment but I have saved it and also included your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the great work.

  4. I relish, lead to I discovered just what I used to be having a look for. You’ve ended my 4 day lengthy hunt! God Bless you man. Have a great day. Bye

Leave a Reply

Your email address will not be published. Required fields are marked *