Building a Secure PHP User Registration and Login System with Roles

Learn how to create a robust user registration and login system in PHP using SQL and password hashing. Plus, add user roles to implement role-based access control for increased security.

Building a Secure PHP User Registration and Login System with Roles
Building a Secure PHP User Registration and Login System with Roles

In today's world, user registration and login systems are critical components of many web applications. These systems allow users to create accounts, log in, and access personalized content or services. Creating a secure, robust registration and login system can be a complex task, but it is essential to protect user information and prevent unauthorized access.

In this article, we have created a PHP project for registering and logging in users. The project uses SQL to store user information and password hashing to secure the user's data. The project consists of three files: "register.php" for user registration, "login.php" for user login, and "logout.php" for logging out.

First, we'll need to create a MySQL database and a table to store user information. Here's an example SQL script to create the database and table:

CREATE DATABASE example_db;
USE example_db;

CREATE TABLE users (
  id INT(11) AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(50) NOT NULL UNIQUE,
  password VARCHAR(255) NOT NULL
);

This will create a database called "example_db" and a table called "users" with three columns: "id" (an auto-incrementing integer that serves as the primary key), "username" (a unique string that will be used as the user's login name), and "password" (a hashed string that will be used to store the user's password).

Next, let's create the PHP files for the project. We'll need a "register.php" file to allow users to create an account, a "login.php" file to allow users to log in, and a "logout.php" file to allow users to log out.

Here's the code for the "register.php" file:

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $username = $_POST["username"];
  $password = $_POST["password"];

  $dbhost = "localhost";
  $dbuser = "username";
  $dbpass = "password";
  $dbname = "example_db";

  $conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

  $hashed_password = password_hash($password, PASSWORD_DEFAULT);

  $sql = "INSERT INTO users (username, password) VALUES ('$username', '$hashed_password')";

  if (mysqli_query($conn, $sql)) {
    echo "User registered successfully";
  } else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
  }

  mysqli_close($conn);
}

?>

<h2>Register</h2>

<form method="post">
  <label for="username">Username:</label>
  <input type="text" name="username" required><br>

  <label for="password">Password:</label>
  <input type="password" name="password" required><br>

  <button type="submit">Register</button>
</form>

This code uses the "password_hash" function to hash the user's password before storing it in the database. It also uses the "mysqli" extension to connect to the database and execute the SQL query.

Here's the code for the "login.php" file:

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $username = $_POST["username"];
  $password = $_POST["password"];

  $dbhost = "localhost";
  $dbuser = "username";
  $dbpass = "password";
  $dbname = "example_db";

  $conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

  $sql = "SELECT * FROM users WHERE username = '$username'";
  $result = mysqli_query($conn, $sql);

  if (mysqli_num_rows($result) == 1) {
    $row = mysqli_fetch_assoc($result);

    if (password_verify($password, $row["password"])) {
      session_start();
      $_SESSION["username"] = $username;
      header("Location: index.php");
    } else {
      echo "Invalid password";
    }
  } else {
    echo "User not found";
  }

  mysqli_close($conn);
}

Let's add an example with ROLES.

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $username = $_POST["username"];
  $password = $_POST["password"];

  $dbhost = "localhost";
  $dbuser = "username";
  $dbpass = "password";
  $dbname = "example_db";

  $conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);

  $sql = "SELECT * FROM users WHERE username = '$username'";
  $result = mysqli_query($conn, $sql);

  if (mysqli_num_rows($result) == 1) {
    $row = mysqli_fetch_assoc($result);

    if (password_verify($password, $row["password"])) {
      session_start();
      $_SESSION["username"] = $username;
      $_SESSION["role"] = $row["role"];
      header("Location: index.php");
    } else {
      echo "Invalid password";
    }
  } else {
    echo "User not found";
  }

  mysqli_close($conn);
}

?>

This updated script adds a "role" column to the "users" table in the database, which stores the user's role (e.g. "guest", "user", or "administrator"). When a user logs in, their role is retrieved from the database and stored in the "role" session variable.

With this information, you can implement role-based access control in your PHP application, which allows you to restrict access to certain parts of your website based on the user's role. For example, you could use the following code to check if a user is an administrator:

<?php

session_start();

if (!isset($_SESSION["username"]) || $_SESSION["role"] != "administrator") {
  header("Location: login.php");
  exit;
}

// administrator-only content goes here

?>

This code checks if the user is logged in and has an "administrator" role. If not, the user is redirected to the login page. If the user is an administrator, they can access the administrator-only content.

You can implement similar checks for other roles, such as "user" or "guest", to restrict access to different parts of your website. By using role-based access control, you can create a more secure and personalized user experience for your website.

Creating a user registration and login system is an essential task for many web applications, and it is critical to create a secure and robust system to protect user information and prevent unauthorized access. With the PHP project we have created, you now have a solid foundation to build upon and implement in your own projects. By utilizing SQL to store user information and password hashing to secure the user's data, you can create a user registration and login system that is both safe and reliable. Remember to always be vigilant in protecting user information and keeping your code up to date with the latest security practices.

Our website is for sale! The domain and website has been running for more than 3 years, but it's time to part with it. There is no price, so I consider any offer. Contact us if you are interested in buying in the feedback form, we will discuss options, price and details for transferring the site. (script, database and everything else for the site to work).