Lab 1: Form Handling & Validation
Additional Resources
Section titled “Additional Resources”- Form Submission: A Step-by-Step Guide
- Server-Side Input Validation
- PHP Sessions
- Input Methods (GET/POST)
- Bootstrap 5 Getting Started ↗
- Bootstrap 5 Forms ↗
Overview
Section titled “Overview”In this lab, you will build a Product Feedback Form using vanilla PHP (no framework). You will create an HTML form that submits data via POST to a separate processing script, validate all inputs on the server side, and use the Post-Redirect-Get (PRG) pattern to prevent duplicate submissions. After successful processing, a flash message stored in $_SESSION will communicate the result back to the user.
Learning Objectives
Section titled “Learning Objectives”By completing this lab, you will:
- Create reusable layout includes (
header.php,footer.php) and include them withrequire. - Build an HTML form that submits data via POST to a separate processing script.
- Retrieve and sanitize user input using
filter_input()andtrim(). - Implement server-side validation with an
$errorsarray and display error messages. - Build a sticky form that preserves user input when validation fails.
- Apply the Post-Redirect-Get (PRG) pattern to prevent duplicate form submissions.
- Use
$_SESSIONto store and display flash messages after a redirect. - Escape output with
htmlspecialchars()to prevent XSS.
Prerequisites
Section titled “Prerequisites”Before starting this lab, ensure you have:
- A local PHP development environment (e.g., XAMPP or WAMP).
- Basic understanding of HTML forms and PHP syntax.
- Familiarity with PHP sessions (
session_start(),$_SESSION).
Project Structure
Section titled “Project Structure”Create the following folder and file structure inside your project directory:
project/├── includes/│ ├── header.php│ └── footer.php├── feedback.php└── process-feedback.phpStep 1: Create the Partials
Section titled “Step 1: Create the Partials”Objective: Create reusable layout files that will be included in every page.
Instructions
Section titled “Instructions”- Create an
includes/folder in your project directory. - Inside
includes/, create two files:header.phpandfooter.php. - Write the code for each file based on the requirements below.
Requirements
Section titled “Requirements”| File | Must Include |
|---|---|
header.php | The HTML5 doctype, a <head> section with Bootstrap 5 CSS and JS linked from CDN (see the Bootstrap Getting Started ↗ page for the CDN links), an opening <body> tag, and an opening <div> with the Bootstrap container mt-4 classes. Use a $pageTitle variable for the <title> tag content. |
footer.php | The closing </div> for the container, and the closing </body> and </html> tags. |
Step 2: Build the Feedback Form Page
Section titled “Step 2: Build the Feedback Form Page”Objective: Create feedback.php, the page that displays the feedback form, shows flash messages after a redirect, and redisplays validation errors with preserved input.
Instructions
Section titled “Instructions”Create a file named feedback.php in your project root. This file must handle the following responsibilities in order:
- Start the session at the very top of the file (before any HTML output).
- Check for a flash message in
$_SESSION['flash_message']. If one exists, store it in a local variable, thenunset()it from the session. - Check for validation errors in
$_SESSION['errors']. If they exist, store them in a local variable, thenunset()them. - Retrieve sticky form data from
$_SESSION['form_data'](if present), store it in a local variable, thenunset()it. - Set
$pageTitleand includeincludes/header.php. - Display the flash message (if one was retrieved) inside a Bootstrap
alert alert-successdiv. - Display validation errors (if any were retrieved) inside a Bootstrap
alert alert-dangerdiv. You can either show them as a list or as individual alerts. - Build the HTML form with the specifications below.
- Include
includes/footer.php.
Form Field Specifications
Section titled “Form Field Specifications”Your form must use method="POST" and action="process-feedback.php". It should contain the following fields styled with Bootstrap form classes:
| Field | Type | name Attribute | Notes |
|---|---|---|---|
| Product Name | Text input | product_name | Required. Preserve the submitted value when redisplaying the form after a validation error. |
| Rating | Select dropdown | rating | Options: 1 through 5. Include a disabled default option with the text “Choose a rating”. Preserve the selected value after a validation error. |
| Email input | email | Required. Preserve the submitted value after a validation error. | |
| Comments | Textarea | comments | Required. Preserve the submitted value between the opening and closing textarea tags after a validation error. |
Add a Submit button with Bootstrap’s btn btn-primary classes.
Step 3: Build the Processing Script
Section titled “Step 3: Build the Processing Script”Objective: Create process-feedback.php, the script that receives the form data, validates it, and redirects back to the form page with either errors or a success message.
Instructions
Section titled “Instructions”Create a file named process-feedback.php in your project root. This file must do the following:
- Start the session at the top.
- Guard against non-POST requests: check
$_SERVER['REQUEST_METHOD']. If it is notPOST, redirect tofeedback.phpand stop execution. - Retrieve all four inputs using
filter_input()andtrim(). - Initialize an empty
$errorsarray. - Validate each field according to the rules in the table below. For every failed rule, add an appropriate error message string to the
$errorsarray. - If errors exist:
- Store the
$errorsarray in$_SESSION['errors']. - Store the submitted form data in
$_SESSION['form_data']as an associative array (so the form page can repopulate the fields). - Redirect to
feedback.phpand stop execution.
- Store the
- If no errors:
- Store a success message (e.g., “Thank you! Your feedback has been submitted.”) in
$_SESSION['flash_message']. - Redirect to
feedback.phpand stop execution.
- Store a success message (e.g., “Thank you! Your feedback has been submitted.”) in
Validation Rules
Section titled “Validation Rules”| Field | Rule(s) |
|---|---|
| Product Name | Must not be empty. |
| Rating | Must be a valid integer between 1 and 5. Use filter_input() with FILTER_VALIDATE_INT to retrieve and validate in one step. |
Must not be empty. If not empty, must be a valid email format. Use filter_var() with FILTER_VALIDATE_EMAIL for format validation. | |
| Comments | Must not be empty. |
Step 4: Understanding the PRG Flow
Section titled “Step 4: Understanding the PRG Flow”Now that you have built both files, let’s trace the full request cycle to understand how the Post-Redirect-Get pattern works.
Success Path
Section titled “Success Path”- The user fills out the form on
feedback.phpand clicks Submit. - The browser sends a POST request to
process-feedback.php. - The server validates the input. All fields are valid.
- The server stores a success message in
$_SESSION['flash_message']. - The server responds with a redirect (
Location: feedback.php). - The browser follows the redirect and sends a GET request to
feedback.php. feedback.phpreads$_SESSION['flash_message'], displays it, and unsets it.- If the user refreshes the page, only the GET request repeats. No duplicate POST.
Error Path
Section titled “Error Path”- The user submits the form with invalid data.
- The browser sends a POST request to
process-feedback.php. - The server validates the input and finds errors.
- The server stores
$errorsand the submitted form data in$_SESSION. - The server responds with a redirect back to
feedback.php. - The browser follows the redirect (GET).
feedback.phpreads the errors and form data from the session, displays the errors, repopulates the form fields, and unsets both session keys.
Step 5: Test and Verify
Section titled “Step 5: Test and Verify”Open feedback.php in your browser and run through the following test scenarios.
Verification Checklist
Section titled “Verification Checklist”- Empty submission: Submit the form with all fields empty. Four validation error messages should appear. No crash or blank page.
- Partial input with invalid email: Fill in only the product name and enter an invalid email (e.g., “notanemail”). Submit. Errors should appear for rating, email format, and comments. The product name and the invalid email should still be in their fields (sticky form).
- Valid submission: Fill in all fields correctly and submit. A green success message should appear. The form fields should be cleared.
- Refresh after success: After seeing the success message, refresh the page. The success message should not reappear, and the browser should not warn about resubmitting form data.
- Direct GET access: Type
process-feedback.phpdirectly in the browser address bar. You should be redirected tofeedback.phpwith no errors displayed.