Skip to content

Lab 8: User Registration

In this lab, you will let customers create accounts in your e-commerce application. You will create a users table, a UserModel for user queries, and a registration form whose submissions are validated and stored with a hashed password. After registering, users are sent to a login page that you will also create in this lab. Lab 9 makes the login form work and adds sessions, route protection, and role-based access control.


By completing this lab, you will:

  • Create a users table with unique email and username columns.
  • Build a UserModel that creates users and looks them up by email or username.
  • Hash passwords with password_hash() before storing them.
  • Validate registration input: required fields, email format, uniqueness, password strength, and password confirmation.
  • Redisplay the form with every error message and the submitted values when validation fails.
  • Display flash messages on public pages.
  • Prevent SQL injection with prepared statements and XSS with output escaping.

Before starting this lab, ensure you have:

  • Completed Lab 4: Session Middleware and Flash Messages. This lab uses SessionMiddleware, the FlashMessage helper, and the BaseController’s render() and redirect() methods.
  • A BaseModel class and a working database connection through PDOService, as used by your ProductsModel.
  • Access to phpMyAdmin for your project database.

Objective: Create the database table that stores user accounts.

Instructions:

  1. Open phpMyAdmin in your browser
  2. Select your project database
  3. Click on the “SQL” tab
  4. Execute the following SQL statement:
SQL Statement to Create the Users Table
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(100) NOT NULL,
username VARCHAR(50) UNIQUE NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL,
role ENUM('admin', 'customer') NOT NULL DEFAULT 'customer',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
  1. Click “Go” to execute the query
  2. Verify the table was created by clicking on the “Structure” tab or running DESCRIBE users;

The UNIQUE constraints on email and username make the database reject duplicate accounts, even if two registrations arrive at the same moment. VARCHAR(255) for password_hash leaves room for longer hash formats in the future. The ENUM restricts role to 'admin' or 'customer'.


Objective: Create a model that stores new users and finds existing users.

Instructions:

  1. Navigate to your app/Domain/Models/ directory
  2. Create a new file named UserModel.php
  3. Start from the following class structure:
app/Domain/Models/UserModel.php
<?php
namespace App\Domain\Models;
use App\Helpers\Core\PDOService;
class UserModel extends BaseModel
{
public function __construct(PDOService $pdoService)
{
parent::__construct($pdoService);
}
/**
* Insert a new user and return the new user's ID.
*
* $data contains the keys first_name, last_name, username, email,
* password (plain text), and role.
*/
public function createUser(array $data): int
{
// TODO
}
/**
* Return the user with the given email address, or null if there is none.
*/
public function findByEmail(string $email): ?array
{
// TODO
}
/**
* Return the user with the given username, or null if there is none.
*/
public function findByUsername(string $username): ?array
{
// TODO
}
/**
* Return true if a user with the given email address already exists.
*/
public function emailExists(string $email): bool
{
// TODO
}
/**
* Return true if a user with the given username already exists.
*/
public function usernameExists(string $username): bool
{
// TODO
}
}
  1. Implement every method marked // TODO, following the behavior described in its comment
  2. Save the file

Hints:

  • In createUser(), hash the password with password_hash($data['password'], PASSWORD_DEFAULT) and store the result in the password_hash column. Never store the plain-text password.
  • Use $this->execute() with named parameters for the INSERT, then return (int) $this->lastInsertId(). lastInsertId() returns a string, so the cast is needed to match the int return type.
  • $this->selectOne() returns false when no row matches, but findByEmail() and findByUsername() must return null in that case. Returning false from a method declared ?array throws a TypeError. Convert the result with ?: null:
return $this->selectOne('SELECT * FROM users WHERE email = :email', ['email' => $email]) ?: null;
  • emailExists() and usernameExists() can call the matching find method and compare the result with null.

Step 3: Display Flash Messages on Public Pages

Section titled “Step 3: Display Flash Messages on Public Pages”

Objective: Render pending flash messages in the public layout, the same way Lab 4 did for the admin layout.

The registration and login pages use the public layout (ViewHelper::loadHeader()), not the admin layout. In Lab 4, you only added FlashMessage::render() to adminHeader.php, so messages added on public pages would never be displayed.

Instructions:

  1. Open your public header view (app/Views/common/header.php or equivalent: the file that ViewHelper::loadHeader() includes)
  2. Inside the main content container, after the navigation bar, add the following code:
app/Views/common/header.php
<!-- Flash Messages -->
<?php if (App\Helpers\FlashMessage::has()): ?>
<div class="mb-4">
<?= App\Helpers\FlashMessage::render() ?>
</div>
<?php endif; ?>
  1. Save the file

Objective: Create a registration form that displays validation errors and keeps the user’s input when validation fails.

Instructions:

  1. Navigate to your app/Views/ directory and create an auth/ folder
  2. Inside app/Views/auth/, create a file named register.php
  3. Copy and paste the following code:
app/Views/auth/register.php
<?php
use App\Helpers\ViewHelper;
ViewHelper::loadHeader($title);
?>
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">
<h3 class="text-center">Create Account</h3>
</div>
<div class="card-body">
<?php if (!empty($errors)): ?>
<div class="alert alert-danger" role="alert">
<ul class="mb-0">
<?php foreach ($errors as $error): ?>
<li><?= hs($error) ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<form method="POST" action="<?= APP_BASE_URL ?>/register">
<div class="mb-3">
<label for="first_name" class="form-label">First Name</label>
<input type="text" class="form-control" id="first_name" name="first_name"
value="<?= hs($old['first_name'] ?? '') ?>" required>
</div>
<div class="mb-3">
<label for="last_name" class="form-label">Last Name</label>
<input type="text" class="form-control" id="last_name" name="last_name"
value="<?= hs($old['last_name'] ?? '') ?>" required>
</div>
<div class="mb-3">
<label for="username" class="form-label">Username</label>
<input type="text" class="form-control" id="username" name="username"
value="<?= hs($old['username'] ?? '') ?>" required>
</div>
<div class="mb-3">
<label for="email" class="form-label">Email Address</label>
<input type="email" class="form-control" id="email" name="email"
value="<?= hs($old['email'] ?? '') ?>" required>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" name="password" required>
<div class="form-text">
Password must be at least 8 characters long and contain at least one number.
</div>
</div>
<div class="mb-3">
<label for="confirm_password" class="form-label">Confirm Password</label>
<input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
</div>
<div class="d-grid gap-2">
<button type="submit" class="btn btn-primary">Register</button>
</div>
</form>
<div class="mt-3 text-center">
<p>Already have an account? <a href="<?= APP_BASE_URL ?>/login">Login here</a></p>
</div>
</div>
</div>
</div>
</div>
<?php ViewHelper::loadFooter(); ?>
  1. Save the file

What you just created:

  • A form that lists every validation error in $errors above the fields
  • Text fields that refill from $old, the values the user submitted, escaped with hs() to prevent XSS
  • Password fields without a value attribute: the server never sends a password back to the browser, so the user retypes it after an error

Objective: Create the login page that users are sent to after registering.

Lab 9 adds the code that processes this form. In this lab, the page only needs to display.

Instructions:

  1. Inside app/Views/auth/, create a file named login.php
  2. Copy and paste the following code:
app/Views/auth/login.php
<?php
use App\Helpers\ViewHelper;
ViewHelper::loadHeader($title);
?>
<div class="row justify-content-center">
<div class="col-md-5">
<div class="card">
<div class="card-header">
<h3 class="text-center">Login</h3>
</div>
<div class="card-body">
<form method="POST" action="<?= APP_BASE_URL ?>/login">
<div class="mb-3">
<label for="identifier" class="form-label">Email or Username</label>
<input
type="text"
class="form-control"
id="identifier"
name="identifier"
value="<?= hs($identifier) ?>"
placeholder="Enter your email or username"
required>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input
type="password"
class="form-control"
id="password"
name="password"
placeholder="Enter your password"
required>
</div>
<div class="d-grid gap-2">
<button type="submit" class="btn btn-primary">Login</button>
</div>
</form>
<div class="mt-3 text-center">
<p>Don't have an account? <a href="<?= APP_BASE_URL ?>/register">Register here</a></p>
</div>
</div>
</div>
</div>
</div>
<?php ViewHelper::loadFooter(); ?>
  1. Save the file

The single identifier field accepts either an email address or a username. In Lab 9, $identifier refills the field after a failed login attempt.


Objective: Create a controller that displays the registration and login forms and processes registrations.

Instructions:

  1. Navigate to your app/Controllers/ directory
  2. Create a new file named AuthController.php
  3. Start from the following class structure:
app/Controllers/AuthController.php
<?php
namespace App\Controllers;
use App\Domain\Models\UserModel;
use App\Helpers\FlashMessage;
use DI\Container;
use PDOException;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
class AuthController extends BaseController
{
public function __construct(Container $container, private UserModel $userModel)
{
parent::__construct($container);
}
/**
* Display the registration form (GET /register).
*/
public function register(Request $request, Response $response, array $args): Response
{
// TODO: Render the registration view with the title 'Create Account',
// no errors, and no previously submitted values.
}
/**
* Process the registration form (POST /register).
*/
public function store(Request $request, Response $response, array $args): Response
{
// TODO: Read the submitted fields, removing surrounding spaces from
// every field except the two passwords.
// TODO: Check the fields against the rules in the table below and
// collect the message of every rule that fails.
// TODO: If any rule failed, redisplay the form with the errors and the
// submitted values (never the passwords), with status 422.
// TODO: Otherwise, create the user as a customer.
// If it succeeds, show a success message and send the user to the login form.
// If the database rejects the insert, show an error message and send
// the user back to the registration form.
}
/**
* Display the login form (GET /login).
*/
public function login(Request $request, Response $response, array $args): Response
{
// TODO: Render the login view with the title 'Login' and an empty identifier.
}
}
  1. Implement every method marked // TODO
  2. Save the file

Validation Rules:

RuleError Message
Every field is filled inAll fields are required.
The email has a valid format (filter_var() with FILTER_VALIDATE_EMAIL)Invalid email format.
The email is not registered yet (emailExists())Email already registered.
The username is not taken yet (usernameExists())Username already taken.
The password is at least 8 characters longPassword must be at least 8 characters long.
The password contains at least one digit (preg_match('/\d/', $password))Password must contain at least one number.
The password and its confirmation matchPasswords do not match.

Hints:

  • The views read these variables, so use them as the $data keys: $title, $errors, and $old in register.php; $title and $identifier in login.php.
  • If any field is empty, add only “All fields are required.” and skip the other rules. Otherwise an empty email would also report “Invalid email format.”
  • render() returns a Response, and a response’s status code can be changed with its withStatus() method.
  • Status 422 (Unprocessable Content) tells the browser that the submission was rejected. Because the form is re-rendered instead of redirected, the error messages and the submitted values do not need to go through the session.
  • createUser() throws a PDOException if the insert fails, for example when another registration with the same email is saved between your emailExists() check and the insert. It does not return 0.
  • Use “Your account has been created. You can now log in.” as the success message and “Registration failed. Please try again.” as the error message.

Objective: Map the registration and login URLs to the AuthController.

Instructions:

  1. Open your app/Routes/web-routes.php file
  2. Add the following import at the top:
use App\Controllers\AuthController;
  1. Add the following routes inside the return static function (Slim\App $app): void { ... } closure, outside the /admin group:
app/Routes/web-routes.php
// TODO: Create a GET route for '/register' that maps to AuthController::class 'register' method
// Set the route name to 'auth.register'
// TODO: Create a POST route for '/register' that maps to AuthController::class 'store' method
// Set the route name to 'auth.store'
// TODO: Create a GET route for '/login' that maps to AuthController::class 'login' method
// Set the route name to 'auth.login'
  1. Save the file

Routes Created:

MethodURIController MethodRoute Name
GET/registerAuthController::register()auth.register
POST/registerAuthController::store()auth.store
GET/loginAuthController::login()auth.login

Submitting the login form returns a “405 Method Not Allowed” error until Lab 9 adds the POST /login route.


  1. Visit http://localhost/your-app-name/register in your browser (replace your-app-name with your project’s folder name in htdocs/)
  2. Fill in all fields with valid data and click “Register”. You should be redirected to the login page, which displays a green “Your account has been created” message.
  3. Refresh the login page. The message should not appear again, and the browser should not ask you to confirm a form resubmission.
  4. Return to the registration page and test each validation rule. Each submission should show the matching message from the table in Step 6, keep the text fields filled in, and leave the password fields empty:
    • Invalid email (for example, notanemail@)
    • The email you registered in step 2
    • The username you registered in step 2
    • A password shorter than 8 characters
    • A password without a number (for example, password)
    • Two different passwords
  5. Submit a form that breaks several rules at once (for example, a taken username and mismatched passwords). Every matching message should appear.
  6. Open your browser’s developer tools, select the Network tab, and submit an invalid form. The POST /register request should have the status 422.
  7. Open phpMyAdmin and browse the users table. The password_hash column should contain a string starting with $2y$ (bcrypt), not the plain-text password, and role should be customer.

Before submitting your lab, verify the following:

  • The users table exists with UNIQUE constraints on email and username
  • UserModel.php exists in app/Domain/Models/ and implements all five methods
  • The public header renders flash messages
  • register.php and login.php exist in app/Views/auth/
  • A valid registration redirects to the login page with a success message
  • Each validation rule displays its message, and invalid submissions return status 422
  • Text fields keep their values after a validation error, and password fields are empty
  • Stored passwords are hashed and new users have the customer role