How to create a user login system in PHP

Overview

In this shot, we will create a user login system in our PHP application. Almost every application we use today requires an authentication system.

Let’s get started.

Prerequisites

  • A PHP/SQL environment
  • A database with a User table and insert at least one user

We can create a database set by using the following script:

DROP DATABASE IF EXISTS `university`;
CREATE DATABASE IF NOT EXISTS `university`;
USE `university`;
DROP TABLE IF EXISTS `User`;
CREATE TABLE `User` (
`id` INT unsigned NOT NULL AUTO_INCREMENT,
`username` VARCHAR(50) COLLATE utf8_unicode_ci NOT NULL,
`password` VARCHAR(150) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `User` (`id`, `username`, `password`) VALUES (1, "admin", "admin123");

Note: We can learn more about SQL in this shot.

Files structure

To build a basic login system we’ll use the following files structure:

  • index.php: The landing page with the login form and the processing code.
  • home.php: The dashboard for the connected user.
  • config.php: The database connection.

Our workspace must be clean to create all those files.

For CLI, use the following commands:

# create the directory for your program
mkdir dashord
cd dashbord
# create files
touch index.php home.php config.php

Build the front-end

index.php

For now, we’ll have a basic form for username and password.

<h1>User Login</h1>
<form action="" method="post">
  <input type="text" id="username" name="username" placeholder="username">
  <input type="password" id="password" name="password">
  <input type="submit" value="Login">
</form>

We can view it below:

User login form

home.php

It is a basic welcome note to the connected user.

<h1> 
    Welcome, username
</h1>

Note: We can consider this shot to do front-end validation.

Build the back-end

Setup database connection

First, let’s configure the database connection in config.php:

<?php
define('MYSQL_USER', 'root');
define('MYSQL_PASSWORD', 'root');
define('MYSQL_HOST', 'localhost');
define('MYSQL_DATABASE', 'university');
/**
* PDO options:
* - error mode set to exception
* - emulated prepared stmt turned off
*/
$dsn = 'mysql:host=' . MYSQL_HOST . ';dbname=' .MYSQL_DATABASE;
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_PERSISTENT => true,
);
// Connection
try {
$pdo = new PDO($dsn, MYSQL_USER, MYSQL_PASSWORD, $options);
} catch (PDOException $e) {
die(
"ERROR: Database connection error" .
$e->getMessage()
);
}

We can now connect to our database using PDO.

Note: We can learn more about how to connect to an SQL database using PDO here

Handle form submission

We’ll implement the script to process the form submission in index.php.

First, we need to check if the user has sent the form.

if($_SERVER['REQUEST_METHOD'] == 'POST') {
// processessing code here
}

Once we are sure that the user has submitted the form, we first require the database connection, then we can initialize variables to an empty string:

require_once "config.php";
$username = $password = "";

Next, we do basic input validation and assign the appropriate values to our initial variables:

<?php
if (empty(trim($_POST['username']))) {
echo 'Enter the username';
} else {
$username = trim($_POST['username']);
}
if (empty(trim($_POST['password']))) {
echo 'Enter the password';
} else {
$password = trim($_POST['password']);
}

Now we have the user-submitted credentials (login and password). Let’s compare it with the existing one:

<?php
$sql = 'SELECT id, username, password FROM User WHERE username = ?';
if($stmt = $pdo->prepare($sql)) {
$stmt->bindParam(1, $param_username, PDO::PARAM_STR);
$param_username = $username;
if($stmt->execute()) {
// First check if the user exists, then verify the password
if($stmt->rowCOunt() == 1) {
if($row = $stmt->fetch()) {
$id = $row['id'];
$username = $row['username'];
if($_POST['password'] == $row['password']) {
header('location:home.php');
} else {
// Invalid password, echo a general error msg
echo "Username or password not correct";
}
} else {
// username no exists
echo "Username or password not correct";
}
} else {
echo "Oops, something went wrong. Try again later";
}
// close stmt
unset($stmt);
}
}

We use prepared statement to check whether the submitted credential matches one that already exists in the database. We first check for the username, then the password. If the submitted credential matches, we redirect the user to the home (header('location:home.php');). If not, we print an error message.

Wrap up

To build our basic authenticate system, we did proceed as follows:

  1. We build the front-end, the form the user see and use to submit their credentials (index.php).
  2. We set up the database connection (config.php).
  3. We handle the submitted data (index.php).
  4. We redirect the successful user to the protected page (home.php).

Happy coding!

Free Resources