4 Steps Simple User Login System With PHP MySQL – Free Download!

Welcome to a tutorial on how to create a simple user login system with PHP and MYSQL. So you have just started a project and want to secure the administration panel? Maybe create a “members only” section?

A simple user login system consists of the following essential components:

  • A user database table to keep the emails and passwords.
  • PHP user library to manage the users.
  • The login page itself.
  • Finally, protecting all the pages.

This guide will walk you through an example of how to do these exactly – Read on to find out!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TABLE OF CONTENTS

Download & Notes Login System Useful Bits & Links
Tutorial Video The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • Create a database and import 1-users.sql.
  • Change the database settings to your own in 2-user-lib.php.
  • Access 3-login.php in your web browser, and that’s all. The Dummy user account is “jon@doe.com” and the password is “123456”.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code in a zip file – I have released it under the MIT License, so feel free to build on top of it if you want to.

 

 

LOGIN SYSTEM WITH PHP MYSQL

All right, let us now get into the details of building a login system with PHP and MYSQL.

 

STEP 1) CREATE A USER DATABASE TABLE

1-users.sql
CREATE TABLE `users` (
  `user_id` int(11) NOT NULL,
  `user_name` varchar(255) NOT NULL,
  `user_email` varchar(255) NOT NULL,
  `user_password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `users`
  ADD PRIMARY KEY (`user_id`),
  ADD UNIQUE KEY `user_email` (`user_email`);
 
ALTER TABLE `users`
  MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

INSERT INTO `users` (`user_id`, `user_name`, `user_email`, `user_password`) VALUES
  (1, 'Jon Doe', 'jon@doe.com', '$2y$10$eGdnkD1EcFdLmPtm0eqQ8OqjjRo6NWrXKDmbieFPKHmRUTmz7iYzi');
Field Description
user_id Primary key, and auto-increment.
user_name The user’s name.
user_email The user’s email address. Unique field to prevent multiple registrations.
user_password The password, which should be encrypted.

Yep, it’s as simple as that. Feel free to add more fields as required.

 

 

STEP 2) PHP USER CLASS

2-user-lib.php
<?php
class Users {
  // (A) CONSTRUCTOR - CONNECT TO DATABASE
  private $pdo = null;
  private $stmt = null;
  public $error = null;
  function __construct () {
    try {
      $this->pdo = new PDO(
        "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET,
        DB_USER, DB_PASSWORD, [
          PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
          PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
      );
    } catch (Exception $ex) { exit($ex->getMessage()); }
  }

  // (B) DESTRUCTOR - CLOSE DATABASE CONNECTION
  function __destruct () {
    if ($this->stmt !== null) { $this->stmt = null; }
    if ($this->pdo !== null) { $this->pdo = null; }
  }

  // (C) GET USER BY ID OR EMAIL
  function get ($id) {
    $sql = sprintf("SELECT * FROM `users` WHERE `user_%s`=?",
      is_numeric($id) ? "id" : "email"
    );
    $this->stmt = $this->pdo->prepare($sql);
    $this->stmt->execute([$id]);
    return $this->stmt->fetch();
  }

  // (D) VERIFY EMAIL PASSWORD - SESSION MUST BE STARTED!
  function login ($email, $password) {
    // (D1) ALREADY SIGNED IN
    if (isset($_SESSION["user"])) { return true; }
    
    // (D2) GET USER
    $user = $this->get($email);
    if (!is_array($user)) { return false; }

    // (D3) VERIFY PASSWORD + REGISTER SESSION
    if (password_verify($password, $user["user_password"])) {
      $_SESSION["user"] = [];
      foreach ($user as $k=>$v) {
        if ($k!="user_password") { $_SESSION["user"][$k] = $v; }
      }
      return true;
    }
    return false;
  }
  
  // (E) SAVE USER
  function save ($name, $email, $pass, $id=null) {
    if ($id===null) {
      $sql = "INSERT INTO `users` (`user_name`, `user_email`, `user_password`) VALUES (?,?,?)";
      $data = [$name, $email, password_hash($pass, PASSWORD_DEFAULT)];
    } else {
      $sql = "UPDATE `users` SET `user_name`=?, `user_email`=?, `user_password`=? WHERE `user_id`=?";
      $data = [$name, $email, password_hash($pass, PASSWORD_DEFAULT), $id];
    }
    try {
      $this->stmt = $this->pdo->prepare($sql);
      $this->stmt->execute($data);
      return true;
    } catch (Exception $ex) {
      $this->error = $ex->getMessage();
      return false;
    }
  }
}

// (F) DATABASE SETTINGS - CHANGE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8");
define("DB_USER", "root");
define("DB_PASSWORD", "");

// (G) CREATE USER OBJECT
$USR = new Users();

Yikes! This looks massive, but keep calm and study closely.

  • (A & B) When $USR = new Users() is created, the constructor will connect to the database. The destructor closes the connection.
  • (C To E) There are only 3 user functions!
    • get() Self-explanatory. Get the user with the given email address or user ID.
    • login() Process login, do checks and stuff.
    • save() To add or update a user. For example, $USR->save("Jane Doe", "jane@doe.com", "123456");
  • (F & G) Database settings and the users object. Doh.

 

 

STEP 3) USER LOGIN PAGE

3-login.php
<?php
// (A) PROCESS LOGIN ON SUBMIT
session_start();
if (isset($_POST["email"])) {
  require "2-user-lib.php";
  $USR->login($_POST["email"], $_POST["password"]);
}
 
// (B) REDIRECT USER IF SIGNED IN
if (isset($_SESSION["user"])) {
  header("Location: 4-index.php");
  exit();
}
 
// (C) SHOW LOGIN FORM OTHERWISE ?>
<?php
if (isset($_POST["email"])) {
  echo "<div id='notify'>Invalid user/password</div>";
}
?>
<form id="login" method="post">
  <strong>MEMBER LOGIN</strong>
  <input type="email" name="email" placeholder="Email" required>
  <input type="password" name="password" placeholder="Password" required>
  <input type="submit" value="Sign In">
</form>

  1. When the login form is submitted, we use the user library to process the login.
  2. If the user is signed in, redirect to the home page.
  3. The login form itself.

 

 

STEP 4) SECURE ALL THE PAGES

4-protect.php
<?php
// (A) "LISTEN" FOR LOGOUT
session_start();
if (isset($_POST["logout"])) {
  unset($_SESSION["user"]);
}
 
// (B) REDIRECT TO LOGIN PAGE IF NOT SIGNED IN
if (!isset($_SESSION["user"])) {
  header("Location: 3-login.php");
  exit();
}

Yes, just include this snippet at the top of all the pages that you want to secure. This should be self-explanatory again – Redirect all users who are not signed in to the login page.

 

 

EXTRA) HOW TO LOGOUT

4-index.php
<?php
require "4-protect.php";
?>

Congrats! You have signed in.
<form method="post">
  <input type="submit" name="logout" value="Logout"/>
</form>

Captain Obvious to the rescue! Notice that if (isset($_POST["logout"])) { unset($_SESSION["user"]); } in 4-protect.php? Simply create a form that will POST a log out to itself.

 

USEFUL BITS & LINKS

That’s it for the tutorial, and here are some stuff and links that might be useful to you.

 

USE HTTPS!

It is not very smart to use http:// and post clear text passwords across the Internet… Switch to use https:// when you can – Most hosting companies should provide a free SSL certificate nowadays, and there are a few affordable ones anyway.

 

LINKS & REFERENCES

 

TUTORIAL VIDEO

 

THE END

Thank you for reading, and that’s it for this tutorial. I hope it has helped you with your project, but please do remember that this guide is ultimately a skeleton frame only – You have to beef up on the security and add access control in your own project. If you have anything to share, feel free to comment below. Good luck, and happy coding!

18 thoughts on “4 Steps Simple User Login System With PHP MySQL – Free Download!”

  1. hai. What a great teacher would you have become and what a great students i would have been if i found you earlier. Thank you very much.

    I wonder what we can do if there are two types of user such as admin and end user.

  2. Thanks for sharing this login PHP / MySQL tutorial. Even me with little experience with programming had no problems implementing this on my web page. code-boxx.com will be my first go to place if I need code in the future. This step by step guide without annoying links to non local scripts that we don’t know what are for, was simply what I needed. You guys are great.

    Thanks again

    John

  3. Hi,
    this web page is great. Thank.
    I’m having trouble with this script.
    I have a parameter: PHP 7.0,
    Thanks for the help, Jeeff

    Parse error: syntax error, unexpected ‘[‘, expecting ‘)’ in /data/web/virtuals/2-user-lib.php on line 28 :

    // (C) GET USER BY EMAIL
    function getByEmail ($email) {
    $this->stmt = $this->pdo->prepare(“SELECT * FROM `users` WHERE `user_email`=?”);
    $this->stmt->execute([$email]);
    return $this->stmt->fetch();
    }

    1. Nothing is wrong with the library, this works:

      require "2-user-lib.php";
      $user = $USR->getByEmail("john@doe.com");
      print_r($user);

      The error message already gave you a hint – One of your own customizations has a syntax error somewhere. E.G. Array or function not properly closed – function($email]; OR $xyz = ["red", "green";

    1. With die() or exit() – Will immediately stop and send the redirect header alone.

      Without die() or exit()- Will send redirect header AND HTML. Does not make sense, just a waste of system resources.

  4. hello, excellent tutorial and easy to implement for a novice like me.

    also, can you tell me how to display different content to different user after successul login?

    i want to manually set different url redirection to different user after successful login.

    it will be of great help. thanks in advance.

    1. Just change 3d-index.php to load different PHP pages.

      if (!is_array($_SESSION['user'])) { 
        header("Location: 3a-login.php"); 
        die(); 
      }
      
      if ($_SESSION['user']['email'] == "FOO") { require "PAGE-FOR-FOO.PHP" }
      else { require "PAGE-FOR-BAR.PHP"; }
  5. Thanks so much for the guide, it’s very helpful. Wondering if you could please help me with something – I want to display the user_name on the page when a user logs in successfully but I’m having trouble accessing the array data – I have the sessions set :

    and have tried each of these but with no success..

    <?php
    echo $users[1]['user_name'];

    echo $users[' user_name'];

    foreach($results['user'] as $result) {
    echo $result['user_name'], '’;
    }

    print_r(array_column($user, ‘user_name’));

    ?>

    Thanks in advance!

Leave a Comment

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