php-programming-banner

Basic Authentication with PHP & MySQL

Lately, I have been receiving a lot of emails on how to create a basic login and registration system by using plain PHP and MySQL. I have made this series just to teach you about the Basic Authentication, i.e. registering a user into the database and then logging the user to the system. We will also encrypt the password using PHP’s native function which uses the Bcrypt Algorithm. In a nutshell, this series will contain seven videos. What will you learn? At the end of this series, you will learn to create a basic authentication system for your application using PHP and MySQL.

  1. Create Database Schema and Folder Structure
  2. Create a Simple Login Page
  3. Create a Simple Registration Page
  4. Create Connection with the database
  5. Register User in the Database
  6. Authenticate User into the System
  7. Securing Pages from Invalid User

Create Database Schema and Folder Structure

Step 1. Create a Database with the name tutorials

create-database

Step 2. Create a table inside the tutorials database with the name t_login

--
-- Table structure for table `t_login`
--

CREATE TABLE `t_login` (
  `id` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `password` varchar(500) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `t_login`
--
ALTER TABLE `t_login`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `t_login`
--
ALTER TABLE `t_login`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

Step 3. Create Folder Structure to work with

folder structure




Create a Simple Login Page

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?php 
$title = 'Login Page';
include 'includes/_header.php';
?>

<div class="container">
    <div class="row">
        <div class="col s1"></div>
        <div class="col s10">
            <form method="POST" action="process/authUser.php">
            <table>
                <tr>
                    <th>Login Form</th>
                </tr>
                <tr>
                    <td>Username</td>
                    <td><input type="text" name="username"></td>
                </tr>
                <tr>
                    <td>Password</td>
                    <td><input type="password" name="password"></td>
                </tr>
                <tr>
                    <td></td>
                    <td><button type="submit">Login</button></td>
                </tr>
            </table>
            </form>
        </div>
        <div class="col s1"></div>
    </div>
</div>

<?php 
    include 'includes/_footer.php';
?>

Create a Simple Registration Page

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?php 
$title = 'Registration Page';
include 'includes/_header.php';
?>

<div class="container">
    <div class="row">
        <div class="col s1"></div>
        <div class="col s10">
            <form method="POST" action="process/registerUser.php">
            <table>
                <tr>
                    <th>Registration Form</th>
                </tr>
                <tr>
                    <td>Username</td>
                    <td><input type="text" name="username"></td>
                </tr>
                <tr>
                    <td>Password</td>
                    <td><input type="password" name="password"></td>
                </tr>
                <tr>
                    <td></td>
                    <td><button type="submit">Register</button></td>
                </tr>
            </table>
            </form>
        </div>
        <div class="col s1"></div>
    </div>
</div>

<?php 
    include 'includes/_footer.php';
?>

 

Create Connection with the Database

This class contains all the business logic for the application that deals with the database transaction. This way the code looks cleaner and more maintainable.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php


class DBConnect {

    private $db = NULL;

    const DB_SERVER = "localhost";
    const DB_USER = "root";
    const DB_PASSWORD = "";
    const DB_NAME = "tutorials";

    public function __construct() {
        $dsn = 'mysql:dbname=' . self::DB_NAME . ';host=' . self::DB_SERVER;
        try {
            $this->db = new PDO($dsn, self::DB_USER, self::DB_PASSWORD);
        } catch (PDOException $e) {
            throw new Exception('Connection failed: ' .
            $e->getMessage());
        }
        return $this->db;
    }
}

?>

The above code is used to create connection with the database. It uses PDO class, the PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP. Each database driver that implements the PDO interface can expose database-specific features as regular extension functions. It is the preferred way for making connection to the database.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php


class DBConnect {

    private $db = NULL;

    const DB_SERVER = "localhost";
    const DB_USER = "root";
    const DB_PASSWORD = "";
    const DB_NAME = "tutorials";

    public function __construct() {
        $dsn = 'mysql:dbname=' . self::DB_NAME . ';host=' . self::DB_SERVER;
        try {
            $this->db = new PDO($dsn, self::DB_USER, self::DB_PASSWORD);
        } catch (PDOException $e) {
            throw new Exception('Connection failed: ' .
            $e->getMessage());
        }
        return $this->db;
    }

    // encrypt the password and create a new entry into the database
    public function saveUser ($username, $password) {
        $newPassword = password_hash($password, PASSWORD_DEFAULT);

        $sql = 'INSERT INTO t_login (username,password) VALUES (?,?)';

        $stmt = $this->db->prepare ($sql);

        return $stmt->execute ([$username, $newPassword]);
    }

    private function checkUserByUsername ($username) {
        $sql = 'SELECT * FROM t_login WHERE username=?';

        $stmt = $this->db->prepare ($sql);

        $stmt->execute ([$username]);

        $user = $stmt->fetchAll();

        if (count ($user) == 1) {
            return $user;
        }

        return null;
    }
    public function authUser ($username, $password) {
        $user = $this->checkUserByUsername ($username);

        if (! empty($user)) {
            if (password_verify ($password, $user[0]['password'])) {
                session_start();
                $_SESSION ['userID'] = $user[0]['id'];
                $_SESSION ['username'] = $username;
                return true;
            } else {
                return false;
            }
        }

        return false;
    }
    
}



?>

In this class, we create a constructor which holds the code for making connection to the database. As soon as the object of this class is created, it gets initialized and a connection to the database is made. A separate class for holding database connection and all the related business logic helps to maintain the modularity of the application.

Register User in the Database

Create a file with the name registerUser.php. The registerUser.php file lies inside process folder. This file is responsible for receiving the data sent from the registeration form with the help of $_POST superglobal variable. We pass the name of the input field we want to fetch the data from and save it to its corresponding variable.

Then we load the DBConnect.php class which resides inside classes folder and create its object. We use the object to access the function that we created inside of the DBConnect class.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<?php

$username = $_POST['username'];
$password = $_POST['password'];

require_once ('../classes/DBConnect.php');

$db = new DBConnect ();

if ($db->saveUser ($username, $password)) {
    echo "<h2>You have been registered Successfully!</h2>";
    header('Refresh: 2;url=http://localhost/tutorials/basic-auth/home.php');
    die();
} else {
    echo "<h2>There was some problemo!</h2>";
    header('Refresh: 2;url=http://localhost/tutorials/basic-auth/register.php');
    die();
}

Authenticate User into the Database System

Create a file named authUser.php inside your process folder and paste the following code in it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<?php

$username = $_POST['username'];
$password = $_POST['password'];

require_once ('../classes/DBConnect.php');

$db = new DBConnect ();

if ($db->authUser ($username, $password)) {
    echo "Login Successful! Redirecting...";
    header ('Refresh: 2; url=http://localhost/tutorials/basic-auth/home.php');
    die ();
} else {
    die("Invalid Credentials");
}




Securing Pages from Unauthorised User

If the login is successful we would like to send the user to his/her profile or home page. We do not want any intruder to access the page without having to pass through proper login. Therefore, the pages must only be accessible if the user has been authenticated successfully. For that we must provide some sort of authentication on each page to prevent unauthorised users from accessing it. We do this by using session variables.

Create a new file in the root folder and give it a name as home.php. Copy the following code into the file and save it. Then navigate to the home.php file without passing through the login form and you will be redirected back to the login form. Now, try again, but this time through the login form and you will be able to access the page successfully. 🙂

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<?php

session_start ();
if (! isset ($_SESSION['userID'])) {
	header ('Location: http://localhost/tutorials/basic-auth/');
	die ();
}

include ('includes/_header.php');

?>

Welcome <?= $_SESSION['username']; ?>


<?php
	include ('includes/_footer.php');
?>

Conclusion

I hope you learned the basic authentication successfully. If you have any problem or any query, then you may comment below. I will be very active to solve any of your queries and help you grasp each and every part of it.

For full tutorial series, visit our youtube channel, and don’t forget to subscribe.

One Life, Rise & Shine
Cheers 🙂

2 thoughts on “Basic Authentication with PHP & MySQL”

  1. Pingback: Basic Authentication With PHP And MySql – 1 | Coding Tutes

  2. Pingback: SEO - Tips for Beginners - Varun Shrivastava's Blog

Leave a Reply