How To Create Login Page In php With Database

Last updated on Aug 30, 2016

Milan Sanathara

Php

2

How To Create Login Page In PHP With Database?

In the previous blog, We have learnt about hashing in PHP.Now,In this blog, we will focus on How to create login page in PHP with Database?

This blog will teach you the complete authentication mechanism using hashing in Php. Php Hashing Blog

In this blog we will cover up following topics :

  • Register User.
  • Login & Logout.
  • User Profile.
  • Edit Profile.
  • Delete Account.

First, create a database.And then create a table.

CREATE TABLE IF NOT EXISTS `user` (
  `user_id` int(11) NOT NULL,
  `user_name` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  `name` varchar(200) DEFAULT NULL,
  `address` text,
  `contact_no` text,
  `about` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `user`
--
ALTER TABLE `user`
  ADD PRIMARY KEY (`user_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
  MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT;

Create dbconnect.php

<?php

class db {

    public $host = "localhost"; //host name
    public $user = "root";//database user name
    public $password = "";//database password if set  
    public $database = "database_name"; //database name
    public $con;

    public function Connect() {
        $this->con = mysqli_connect($this->host, $this->user, $this->password, $this->database);

        if (mysqli_errno($this->con)) {
            echo 'Error: ' . mysqli_connect_error();
            exit();
        }
    }

    public function Disconnect() {
        mysqli_close($this->con);
    }

    /**
     * ExecuteQuery function
     * @param string $sql Proivde your sql statements here.
     * @param int $type 1:Select, 2:Insert, 3:Update
     * @return boolean
     */
    public function ExecuteQuery($sql, $type = 1) {
        $returnData;
        try {
            $sql = str_replace("''", "null", $sql);
            $this->Connect();
            //$sql = mysqli_escape_string($this->con, $sql);
            $data = mysqli_query($this->con, $sql);

            if ($type == 1) {
                $returnData = $data;
            }
            if ($type == 2) {
                $returnData = mysqli_insert_id($this->con);
            }
            if ($type == 3) {
                $returnData = mysqli_affected_rows($this->con);
            }

            $this->Disconnect();
        } catch (Exception $exe) {
            $returnData = FALSE;
        }
        return $returnData;
    }

}

Create user-dbop.php for database operation

<?php

if (!isset($_SESSION))
    session_start();
include_once $_SERVER['DOCUMENT_ROOT'] . '/initconfig.php';
include_once 'php-login-form/dbconnect.php';

class User {

    var $dbObj;

    public function __construct() {
        $this->dbObj = new db();
    }

    public function insert($user_name, $password, $name, $address, $contact_no, $about) {
        $password = hash('sha256', $password);
        $sql = " INSERT INTO user"
                . " (user_name,password,name,address,contact_no,about)"
                . " VALUES('$user_name','$password','$name','$address','$contact_no','$about')";
        return $this->dbObj->ExecuteQuery($sql, 2);
    }

    public function update($user_name, $password, $name, $address, $contact_no, $about, $old_password, $user_id) {
        if (empty($password))
            $password = $old_password;
        else
            $password = hash('sha256', $password);
        $sql = " UPDATE"
                . " user "
                . " SET user_name = '$user_name',password = '$password',name = '$name',address = '$address',"
                . " contact_no = '$contact_no',about = '$about'"
                . " WHERE user_id = '$user_id'";
        return $this->dbObj->ExecuteQuery($sql, 3);
    }

    public function select_by_id($user_id) {
        $sql = " SELECT"
                . " user_id,user_name,password,name,address,contact_no,about"
                . " FROM user WHERE user_id = '$user_id'";
        return $this->dbObj->ExecuteQuery($sql, 1);
    }

    public function delete_account($user_id) {
        $sql = " DELETE FROM user WHERE user_id = '$user_id'";
        return $this->dbObj->ExecuteQuery($sql, 3);
    }

    public function login($user_name, $password) {
        $password = hash('sha256', $password);
        $sql = " SELECT"
                . " user_id,name"
                . " FROM user WHERE"
                . " user_name = '$user_name' AND password = '$password'";
        $data = $this->dbObj->ExecuteQuery($sql, 1);
        if (mysqli_num_rows($data) > 0) {
            $fetch_data = mysqli_fetch_assoc($data);
            $_SESSION['user_id'] = $fetch_data['user_id'];
            $_SESSION['name'] = $fetch_data['name'];
            header("location:profile.php");
        } else {
            echo "<script>window.location='index.php';alert('Invalid User Name or Password !!')</script>";
        }
    }

}

?>

 

Create register.php

<form action="register.php" method="post">
                            <div class="form-group">
                                <label for="email">Email:</label>
                                <input type="email" class="form-control" id="email" placeholder="Enter email" name="user_name">
                            </div>
                            <div class="form-group">
                                <label for="pwd">Password:</label>
                                <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="password">
                            </div>
                            <div class="form-group">
                                <label for="name">Name:</label>
                                <input type="text" class="form-control" id="name" placeholder="Enter Your Name" name="name">
                            </div>
                            <div class="form-group">
                                <label for="address">Address:</label>
                                <textarea name="address" id="address" class="form-control">

                                </textarea>
                            </div>
                            <div class="form-group">
                                <label for="name">Contact No:</label>
                                <input type="text" class="form-control" id="name" placeholder="Enter Your Contact No" name="contact_no">
                            </div>
                            <div class="form-group">
                                <label for="name">About:</label>
                                <input type="text" class="form-control" id="name" placeholder="About Your Self" name="about">
                            </div>
                            <button type="submit" class="btn btn-primary" name="register">Register</button>

Add following PHP code in register.php to of the page

<?php
ob_start();
if (isset($_POST['register'])) {
    include_once $_SERVER['DOCUMENT_ROOT'] . '/initconfig.php';
    include_once 'php-login-form/user-dbop.php'; //php-login-form directory
    $objUser = new User();
    $objUser->insert($_POST['user_name'], $_POST['password'], $_POST['name'], $_POST['address'], $_POST['contact_no'], $_POST['about']);
    header('location:index.php');
}
?>

In above file, you can see the initconfig.php file.

What is initconfig.php?

initconfig.php is a custom created a file ,which sets the root path of the server according to the current server.

if ($_SERVER['HTTP_HOST'] == 'localhost/directory_name')
    set_include_path("C:\apache24\htdocs\directory_name\"); //if you are using xampp then it should be C:\xampp\htdocs\directory_name
else
    set_include_path('/your server path');//if you are working locally it does not need to be set

if you don’t want to set global root path then your register.php code should be like following.No need to create initconfig.php

<?php
ob_start();
if (isset($_POST['register'])) {
    include_once $_SERVER['DOCUMENT_ROOT'].'/php-login-form/user-dbop.php';
    $objUser = new User();
    $objUser->insert($_POST['user_name'], $_POST['password'], $_POST['name'], $_POST['address'], $_POST['contact_no'], $_POST['about']);
    header('location:index.php');
}
?>

When user registers, check user-dbop.php file ,The insert function hash the password ,entered by the user and then stores it in the database.

index.php Login screen

<?php
if (isset($_POST['login'])) {
    include_once $_SERVER['DOCUMENT_ROOT'] . '/initconfig.php';
    include_once 'php-login-form/user-dbop.php';
    $objUser = new User();
    $objUser->login($_POST['user_name'], $_POST['password']);
}
?>
<!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">
        <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
        <meta name="description" content="">
        <meta name="author" content="">
        <title>Php Login Form</title>
        <!-- Bootstrap core CSS -->
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">

        <link rel="stylesheet" href="https://fortawesome.github.io/Font-Awesome/assets/font-awesome/css/font-awesome.css">

        <link href='https://fonts.googleapis.com/css?family=Indie+Flower' rel='stylesheet' type='text/css'>
        <style>
            .at_background{
                background: url(back2.jpg) no-repeat center center fixed;
                -webkit-background-size: cover;
                -moz-background-size: cover;
                -o-background-size: cover;
                background-size: cover;
            }
            .at_font{
                color: navy;
                /*font-family: 'Indie Flower', cursive;*/
                font-family: 'Lobster', cursive;
            }
        </style>
    </head>

    <body class="at_background">
        <div style="height: 100px;">

        </div>
        <div class="container bs-docs-container ">
            <div class="row well">
                <div style="">
                    <img src="https://www.alphansotech.com/wp-content/uploads/2015/12/Alphansotech.png"/>
                </div>
                <div class="col-md-9 " role="main">
                    <div class="bs-docs-section">
                        <div class="header clearfix">
                            <h1 class="at_font col-md-8">Php Login Form With Database</h1>
                        </div>
                        <hr>
                        <form action="index.php" method="post">
                            <div class="form-group">
                                <label for="email">Email:</label>
                                <input type="email" class="form-control" id="email" placeholder="Enter email" name="user_name">
                            </div>
                            <div class="form-group">
                                <label for="pwd">Password:</label>
                                <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="password">
                            </div>
                            <button type="submit" class="btn btn-primary" name="login">Login</button>
                            <a href="register.php" class="btn btn-danger">Register</a>
                        </form>
                    </div>
                </div>

            </div>

        </div> <!-- /container -->
    </body>
</html>

When user login, check user-dbop.php file ,The login function hash the password ,and then check with respect to database stored password .

Create profile.php

<?php
if (!isset($_SESSION))
    session_start();
if (empty($_SESSION['user_id'])) {
    header("location:index.php");
    exit();
} else {
    include_once $_SERVER['DOCUMENT_ROOT'] . '/initconfig.php';
    include_once 'php-login-form/user-dbop.php';
    $objUser = new User();
    $user_resource = $objUser->select_by_id($_SESSION['user_id']);
    $user_data = mysqli_fetch_assoc($user_resource);
}
?>
<!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">
        <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
        <meta name="description" content="">
        <meta name="author" content="">
        <link rel="icon" href="../../favicon.ico">

        <title>Php Login Form</title>
        <!-- Bootstrap core CSS -->
        <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
        <script src="//code.jquery.com/jquery-1.10.2.js"></script>
        <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">

        <link rel="stylesheet" href="https://fortawesome.github.io/Font-Awesome/assets/font-awesome/css/font-awesome.css">
        <!--<link href='https://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>-->
        <link href='https://fonts.googleapis.com/css?family=Indie+Flower' rel='stylesheet' type='text/css'>
        <style>
            .at_background{
                background: url(back2.jpg) no-repeat center center fixed;
                -webkit-background-size: cover;
                -moz-background-size: cover;
                -o-background-size: cover;
                background-size: cover;
            }
            .at_font{
                color: navy;
                /*font-family: 'Indie Flower', cursive;*/
                font-family: 'Lobster', cursive;
            }
        </style>
    </head>

    <body class="at_background">
        <div style="height: 100px;">

        </div>
        <div class="container bs-docs-container ">
            <div class="row well">
                <div style="">
                    <img src="https://www.alphansotech.com/wp-content/uploads/2015/12/Alphansotech.png"/>
                </div>
                <div class="col-md-9 " role="main">
                    <div class="bs-docs-section">
                        <div class="header clearfix">
                            <h1 class="at_font col-md-8">User Profile</h1>
                        </div>
                        <hr>
                        <table class="table table-striped">
                            <tr>
                                <th>
                                    User Email
                                </th>
                                <td>
                                    <?= $user_data['user_name']; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>
                                    Name
                                </th>
                                <td>
                                    <?= $user_data['name']; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>
                                    Address
                                </th>
                                <td>
                                    <?= $user_data['address']; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>
                                    Contact No
                                </th>
                                <td>
                                    <?= $user_data['contact_no']; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>
                                    About User
                                </th>
                                <td>
                                    <?= $user_data['about']; ?>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <a href="update-profile.php" class="btn btn-success">Update</a>
                                </td>
                                <td>
                                    <a href="delete_acc.php" class="btn btn-danger">Delete Account</a>
                                    <a href="logout.php" class="btn btn-primary">Logout</a>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>

            </div>

        </div> <!-- /container -->
    </body>
</html>

Create update-profile.php

<?php
if (!isset($_SESSION))
    session_start();
if (empty($_SESSION['user_id'])) {
    header("location:index.php");
    exit();
} else {
    include_once $_SERVER['DOCUMENT_ROOT'] . '/initconfig.php';
    include_once 'php-login-form/user-dbop.php';
    $objUser = new User();
    $user_resource = $objUser->select_by_id($_SESSION['user_id']);
    $user_data = mysqli_fetch_assoc($user_resource);
}
?>
<!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">
        <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
        <meta name="description" content="">
        <meta name="author" content="">
        <link rel="icon" href="../../favicon.ico">

        <title>Php Login Form</title>
        <!-- Bootstrap core CSS -->
        <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
        <script src="//code.jquery.com/jquery-1.10.2.js"></script>
        <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">

        <link rel="stylesheet" href="https://fortawesome.github.io/Font-Awesome/assets/font-awesome/css/font-awesome.css">
        <!--<link href='https://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>-->
        <link href='https://fonts.googleapis.com/css?family=Indie+Flower' rel='stylesheet' type='text/css'>
        <style>
            .at_background{
                background: url(back2.jpg) no-repeat center center fixed;
                -webkit-background-size: cover;
                -moz-background-size: cover;
                -o-background-size: cover;
                background-size: cover;
            }
            .at_font{
                color: navy;
                /*font-family: 'Indie Flower', cursive;*/
                font-family: 'Lobster', cursive;
            }
        </style>
    </head>

    <body class="at_background">
        <div style="height: 100px;">

        </div>
        <div class="container bs-docs-container ">
            <div class="row well">
                <div style="">
                    <img src="https://www.alphansotech.com/wp-content/uploads/2015/12/Alphansotech.png"/>
                </div>
                <div class="col-md-9 " role="main">
                    <div class="bs-docs-section">
                        <div class="header clearfix">
                            <h1 class="at_font col-md-8">User Profile</h1>
                        </div>
                        <hr>
                        <table class="table table-striped">
                            <tr>
                                <th>
                                    User Email
                                </th>
                                <td>
                                    <?= $user_data['user_name']; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>
                                    Name
                                </th>
                                <td>
                                    <?= $user_data['name']; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>
                                    Address
                                </th>
                                <td>
                                    <?= $user_data['address']; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>
                                    Contact No
                                </th>
                                <td>
                                    <?= $user_data['contact_no']; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>
                                    About User
                                </th>
                                <td>
                                    <?= $user_data['about']; ?>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <a href="update-profile.php" class="btn btn-success">Update</a>
                                </td>
                                <td>
                                    <a href="delete_acc.php" class="btn btn-danger">Delete Account</a>
                                    <a href="logout.php" class="btn btn-primary">Logout</a>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>

            </div>

        </div> <!-- /container -->
    </body>
</html>

delete_acc.php

<?php

include_once $_SERVER['DOCUMENT_ROOT'] . '/initconfig.php';
include_once 'php-login-form/user-dbop.php';
$objUser = new User();
$objUser->delete_account($_SESSION['user_id']);
header('location:index.php');

logout.php

<?php

ob_start();
if (!isset($_SESSION))
    session_start();
unset($_SESSION['user_id']);
session_destroy();
header("location:index.php");

See Live Demo & Download Code

[sociallocker]

See the live Demo

Download the complete source code

[/sociallocker]

I hope you will find this post very useful regarding How To Create Login Page In PHP With Database. Let me know any questions if you have in comment regarding Php. I will reply you ASAP.

Have you got a cool idea about Web Application development? Contact us Now to get a free consultation on your idea. Alphanso Tech is rated as one of the best Web Development Company in India.

Post by Milan Sanathara

I am iOS Application Developer with an aspiration of learning new technology and creating a bright future in Information Technology.

2 Responses to How To Create Login Page In php With Database

    • Hello invaderb , It may due to data-table or path issue
      The user_id (from user table) might not have default value or it may not auto-increment,Either you can try by making it Auto-Increment or download the latest source code which I have just updated,Having sql file and remove initconfig path complications.
      If you will download the fresh source code , you need to change only dbconnect file, based on your sql database settings, remaining code does not need to modified,Try it it will work definitely.
      Kindly,first test it in local server.
      Thank You

Leave a Reply

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