Lab 8: User Registration
Additional Resources
Section titled “Additional Resources”- Login System Overview
- User Registration
- Working with the BaseModel class
- Working with the BaseController class
- PHP password_hash() ↗
- OWASP Password Storage Cheat Sheet ↗
- PHP PDO Prepared Statements ↗
- PHP filter_var() ↗
Overview
Section titled “Overview”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.
Learning Objectives
Section titled “Learning Objectives”By completing this lab, you will:
- Create a
userstable with unique email and username columns. - Build a
UserModelthat 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.
Prerequisites
Section titled “Prerequisites”Before starting this lab, ensure you have:
- Completed Lab 4: Session Middleware and Flash Messages. This lab uses
SessionMiddleware, theFlashMessagehelper, and the BaseController’srender()andredirect()methods. - A
BaseModelclass and a working database connection throughPDOService, as used by yourProductsModel. - Access to phpMyAdmin for your project database.
Step 1: Create the Users Table
Section titled “Step 1: Create the Users Table”Objective: Create the database table that stores user accounts.
Instructions:
- Open phpMyAdmin in your browser
- Select your project database
- Click on the “SQL” tab
- Execute the following SQL statement:
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);- Click “Go” to execute the query
- 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'.
Step 2: Create the UserModel Class
Section titled “Step 2: Create the UserModel Class”Objective: Create a model that stores new users and finds existing users.
Instructions:
- Navigate to your
app/Domain/Models/directory - Create a new file named
UserModel.php - Start from the following class structure:
<?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 }}- Implement every method marked
// TODO, following the behavior described in its comment - Save the file
Hints:
- In
createUser(), hash the password withpassword_hash($data['password'], PASSWORD_DEFAULT)and store the result in thepassword_hashcolumn. Never store the plain-text password. - Use
$this->execute()with named parameters for theINSERT, then return(int) $this->lastInsertId().lastInsertId()returns a string, so the cast is needed to match theintreturn type. $this->selectOne()returnsfalsewhen no row matches, butfindByEmail()andfindByUsername()must returnnullin that case. Returningfalsefrom a method declared?arraythrows aTypeError. Convert the result with?: null:
return $this->selectOne('SELECT * FROM users WHERE email = :email', ['email' => $email]) ?: null;emailExists()andusernameExists()can call the matching find method and compare the result withnull.
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:
- Open your public header view (
app/Views/common/header.phpor equivalent: the file thatViewHelper::loadHeader()includes) - Inside the main content container, after the navigation bar, add the following code:
<!-- Flash Messages --><?php if (App\Helpers\FlashMessage::has()): ?> <div class="mb-4"> <?= App\Helpers\FlashMessage::render() ?> </div><?php endif; ?>- Save the file
Step 4: Create the Registration Form View
Section titled “Step 4: Create the Registration Form View”Objective: Create a registration form that displays validation errors and keeps the user’s input when validation fails.
Instructions:
- Navigate to your
app/Views/directory and create anauth/folder - Inside
app/Views/auth/, create a file namedregister.php - Copy and paste the following code:
<?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(); ?>- Save the file
What you just created:
- A form that lists every validation error in
$errorsabove the fields - Text fields that refill from
$old, the values the user submitted, escaped withhs()to prevent XSS - Password fields without a
valueattribute: the server never sends a password back to the browser, so the user retypes it after an error
Step 5: Create the Login Form View
Section titled “Step 5: Create the Login Form View”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:
- Inside
app/Views/auth/, create a file namedlogin.php - Copy and paste the following code:
<?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(); ?>- 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.
Step 6: Create the AuthController
Section titled “Step 6: Create the AuthController”Objective: Create a controller that displays the registration and login forms and processes registrations.
Instructions:
- Navigate to your
app/Controllers/directory - Create a new file named
AuthController.php - Start from the following class structure:
<?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. }}- Implement every method marked
// TODO - Save the file
Validation Rules:
| Rule | Error Message |
|---|---|
| Every field is filled in | All 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 long | Password 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 match | Passwords do not match. |
Hints:
- The views read these variables, so use them as the
$datakeys:$title,$errors, and$oldinregister.php;$titleand$identifierinlogin.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 aResponse, and a response’s status code can be changed with itswithStatus()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 aPDOExceptionif the insert fails, for example when another registration with the same email is saved between youremailExists()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.
Step 7: Register the Routes
Section titled “Step 7: Register the Routes”Objective: Map the registration and login URLs to the AuthController.
Instructions:
- Open your
app/Routes/web-routes.phpfile - Add the following import at the top:
use App\Controllers\AuthController;- Add the following routes inside the
return static function (Slim\App $app): void { ... }closure, outside the/admingroup:
// 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'- Save the file
Routes Created:
| Method | URI | Controller Method | Route Name |
|---|---|---|---|
| GET | /register | AuthController::register() | auth.register |
| POST | /register | AuthController::store() | auth.store |
| GET | /login | AuthController::login() | auth.login |
Submitting the login form returns a “405 Method Not Allowed” error until Lab 9 adds the POST /login route.
Step 8: Test Your Registration Form
Section titled “Step 8: Test Your Registration Form”- Visit
http://localhost/your-app-name/registerin your browser (replaceyour-app-namewith your project’s folder name inhtdocs/) - 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.
- Refresh the login page. The message should not appear again, and the browser should not ask you to confirm a form resubmission.
- 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
- Invalid email (for example,
- Submit a form that breaks several rules at once (for example, a taken username and mismatched passwords). Every matching message should appear.
- Open your browser’s developer tools, select the Network tab, and submit an invalid form. The
POST /registerrequest should have the status422. - Open phpMyAdmin and browse the
userstable. Thepassword_hashcolumn should contain a string starting with$2y$(bcrypt), not the plain-text password, androleshould becustomer.
Verification Checklist
Section titled “Verification Checklist”Before submitting your lab, verify the following:
- The
userstable exists withUNIQUEconstraints onemailandusername -
UserModel.phpexists inapp/Domain/Models/and implements all five methods - The public header renders flash messages
-
register.phpandlogin.phpexist inapp/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
customerrole