Create Simple Login Page with PHP and MySQL

Login page allows the registered user to access the website and manage its account by entering its username and password.

User SESSION is been created on a successful login attempt.

This helps to detect the user is actually logged in or not when going to other web pages and it also helps to display content according to the user.

In this tutorial, I show how you can create a Login page with PHP and MySQL.

Create Simple Login Page with PHP and MySQL


Contents

  1. Table structure
  2. Configuration
  3. HTML
  4. CSS
  5. PHP
  6. Demo
  7. Conclusion

1. Table structure

I am using users table in the tutorial example.

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `password` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Create config.php file for database configuration.

Completed Code

<?php
session_start();
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}

3. HTML

Create a login page layout that has two input type elements for entering username and password and a button to submit the form.

Completed Code

<div class="container">
    <form method="post" action="">
        <div id="div_login">
            <h1>Login</h1>
            <div>
                <input type="text" class="textbox" id="txt_uname" name="txt_uname" placeholder="Username" />
            </div>
            <div>
                <input type="password" class="textbox" id="txt_uname" name="txt_pwd" placeholder="Password"/>
            </div>
            <div>
                <input type="submit" value="Submit" name="but_submit" id="but_submit" />
            </div>
        </div>
    </form>
</div>

4. CSS

/* Container */
.container{
    width:40%;
    margin:0 auto;
}

/* Login */
#div_login{
    border: 1px solid gray;
    border-radius: 3px;
    width: 470px;
    height: 270px;
    box-shadow: 0px 2px 2px 0px  gray;
    margin: 0 auto;
}

#div_login h1{
    margin-top: 0px;
    font-weight: normal;
    padding: 10px;
    background-color: cornflowerblue;
    color: white;
    font-family: sans-serif;
}

#div_login div{
    clear: both;
    margin-top: 10px;
    padding: 5px;
}

#div_login .textbox{
    width: 96%;
    padding: 7px;
}

#div_login input[type=submit]{
    padding: 7px;
    width: 100px;
    background-color: lightseagreen;
    border: 0px;
    color: white;
}

5. PHP

On the form submit check the username and password entered or not. If entered then execute a SELECT query to count records on the basis of username and password.

If the query returns greater than 0 then initialize $_SESSION['uname'] = $uname and redirect to home.php.

If it returns 0 then display the "Invalid username and password message".

Complete Code

<?php
include "config.php";

if(isset($_POST['but_submit'])){

    $uname = mysqli_real_escape_string($con,$_POST['txt_uname']);
    $password = mysqli_real_escape_string($con,$_POST['txt_pwd']);

    if ($uname != "" && $password != ""){

        $sql_query = "select count(*) as cntUser from users where username='".$uname."' and password='".$password."'";
        $result = mysqli_query($con,$sql_query);
        $row = mysqli_fetch_array($result);

        $count = $row['cntUser'];

        if($count > 0){
            $_SESSION['uname'] = $uname;
            header('Location: home.php');
        }else{
            echo "Invalid username and password";
        }

    }

}

Homepage

Create new home.php file.

First, check whether the user is logged or not by checking the $_SESSION['uname'] variable. If it not set then redirect the user to index.php for login.

Created a logout button that destroy the $_SESSION['uname'] variable and redirect to index.php web page on click.

Complete Code

<?php
include "config.php";

// Check user login or not
if(!isset($_SESSION['uname'])){
    header('Location: index.php');
}

// logout
if(isset($_POST['but_logout'])){
    session_destroy();
    header('Location: index.php');
}
?>
<!doctype html>
<html>
    <head></head>
    <body>
        <h1>Homepage</h1>
        <form method='post' action="">
            <input type="submit" value="Logout" name="but_logout">
        </form>
    </body>
</html>

6. Demo

View Demo


7. Conclusion

In this tutorial, I showed how you can create a simple login page with PHP and MySQL.

You must have to initialize the $_SESSION variable to detect the user when traversing to other pages and destroy it when the user clicks the logout buttons.

If you want to know how to create a register page then you can view the following tutorial.

If you found this tutorial helpful then don't forget to share.

44 thoughts on “Create Simple Login Page with PHP and MySQL”

  1. mysqli_fetch_array() expects parameter 1 to be mysqli_result, is the error message I keep getting. Any idea on how to fix this?

    Reply
  2. Hi,
    I wanted to execute this code on Xampp server and was getting error?
    could you please guide with steps to execute this code.

    Reply
  3. Hello
    I’m trying to add a login page to a website that I’ve built using Dreamweaver CS5 and found your template which I attempted to add to the site.
    I’ve tried to follow your directions on how to tailor it to my own site but I’m afraid my level of knowledge seems to be lacking. I created a user database using MS Access but can’t see how to import your user file into it.
    Could you please give me a little more help on how to add the login page.
    Thanks

    Reply
  4. Important to note that this system is using unhashed passwords. You’d not want to be storing or passing raw passwords in any production machine. Better to store a salt and a hash of the password and check against that. It’s only 2 more steps and will provide a much more secure environment.

    Reply
  5. Dear Yogeh
    i need some suggestion from you
    i am freelance developer
    so for my toll was vb6
    now i want to go for web application with following combination please suggest me any missing or more rapid tech
    HTML5,CSS3,JAVASCRIPT
    PHP7.3 AND MYSQL
    SHALL I START WITH CI OR LARVEL FRAME WORK?
    THANK YOU
    ANAND MB

    Reply
  6. Thank You! It’s really nice, and easy to follow.
    Could You provide an example to automatically log out users after a given time (like 30 minutes) please? Currently users remain logged in even after a day, unless they click on logout.

    Reply
  7. Thanks for posting! Quick questions:
    1. I do not see were following authorization that the sql connection and result is closed. Should this be done somewhere following a successful login?
    2. Will the $_Session variable be destroyed should the user simply exit from any index or any other page associated with the website and NOT exit gracefully via ‘Logout’?

    Reply
  8. Hi, your work is great. So now i would like to know how do you link both registration and login form since you did them separately?

    Reply
  9. Hi! I’m just wondering, how would I link different homepages? Like if I had 2 users and each of them needed a separate dashboard to go to, how would I direct them to different pages?

    Reply
  10. Hi
    thanks for simple guidelines. I am facing an error, when i press login.

    ( ! ) Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, bool given in ——————————-\index.php on line 15

    i tried also to run in phpmyadmin but it failed to run the command.
    i am using WAMPP latest version with PHP7.3 and MariaDB 10.4.

    Can you guide me, how i can i make it fix 🙁

    Reply

Leave a Comment