Project: Contact form
Overview of the 5-lesson contact form project: sessions, files and validation together.
Project: Contact form
In this 5-lesson project you'll build a contact form. Each lesson adds one piece, and by the final lesson you'll complete a working mini application.
You'll use what you learned in previous groups: HTML forms, $_POST, htmlspecialchars, $_FILES, move_uploaded_file and $_SESSION. Throughout the project you'll design a ContactMessage class that holds name, email and message. Then you'll add functions that render the form, validate it, handle file uploads and store messages in a session.
Project roadmap
The project has five lessons. In the second lesson you'll build the form skeleton with a renderForm() function: an HTML form with name, email and message fields. In the third you'll add validateMessage() to check for empty fields and email format, using filter_var and FILTER_VALIDATE_EMAIL. In the fourth you'll add handleUpload() for file upload integration, working with $_FILES and move_uploaded_file. In the final lesson you'll combine all parts with processSubmission() and store messages in $_SESSION.
Exercise Define the ContactMessage class
Write the first piece of this project. Define a class named ContactMessage. Add public string $name = "";, public string $email = ""; and public string $message = ""; properties. Then create an instance with $m = new ContactMessage();, set the name with $m->name = "Alex"; and print it with echo $m->name;.
Show example solution
Declare the class with class ContactMessage { ... }, add public string $name = "";, public string $email = ""; and public string $message = "";. Create an instance with $m = new ContactMessage();, set the name with $m->name = "Alex"; and print with echo $m->name;.
Example solution:
<?php
// Skeleton class for the contact form project
class ContactMessage {
public string $name = "";
public string $email = "";
public string $message = "";
}
$m = new ContactMessage();
$m->name = "Alex";
echo $m->name;
Test yourself
-
Why is validation important in a contact form?
- To make the form look nicer
- To increase server memory
- To prevent empty or invalid data from being processed
- To write less HTML
Show answer
To prevent empty or invalid data from being processed — Correct. Validation prevents empty or invalid data from being processed, so junk data doesn't reach your database or email.
-
Complete the class name
class ____ { public string $name = ""; public string $email = ""; public string $message = ""; }Show answer
class ContactMessage { public string $name = ""; public string $email = ""; public string $message = ""; } -
Match the project concepts
- ContactMessage
- Message data
- renderForm
- Form output
- validateMessage
- Validation
- $_FILES
- File upload