π§© Module 7: Working with Forms and User Input
Objective: Learn how to collect, validate, and sanitize user data in PHP using HTML forms,
$_POST, and $_GET, while ensuring security and data integrity.
πΉ 1. Introduction to Forms and User Input
Forms allow users to send data to the server β like login info, comments, or search queries.
PHP processes that data using superglobal variables like $_POST and $_GET.
π§© Example Form
<form method="POST" action="welcome.php">
Name: <input type="text" name="username"><br>
<input type="submit" value="Submit">
</form>
And in welcome.php:
<?php
echo "Welcome, " . $_POST['username'];
?>
β When the form is submitted, PHP captures the input and displays it.
πΉ 2. Understanding Form Methods: GET vs POST
| Method | Data Location | Use Case | Example |
|---|---|---|---|
| GET | Appends data to the URL | Reading/searching | page.php?name=Yogi |
| POST | Sends data in the HTTP body | Submitting forms, passwords | Used for login or registration |
π§ Rule of Thumb:
- Use GET for things that donβt change server data.
- Use POST for things that do change or contain sensitive info.
πΉ 3. Handling Form Data Securely
Before using user input in your scripts, always:
- Validate: Check if the input is in the right format (email, number, etc.)
- Sanitize: Remove unwanted or malicious characters
- Escape: Convert special characters to HTML-safe symbols
Sanitizing Input
<?php
$name = htmlspecialchars($_POST['name']);
?>
Prevents HTML or JavaScript injection and converts <script> into harmless text.
Validating Input
<?php
$email = $_POST['email'];
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email!";
} else {
echo "Invalid email format.";
}
?>
Combining Validation + Sanitization
<?php
$email = filter_input(INPUT_POST, "email", FILTER_SANITIZE_EMAIL);
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Thanks, $email is valid!";
} else {
echo "Invalid email.";
}
?>
πΉ 4. The $_SERVER["REQUEST_METHOD"] Check
To prevent your page from executing code before submission:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Process form
}
?>
This ensures your code only runs after form submission.
πΉ 5. Error Messages and Required Fields
Good forms provide feedback. Hereβs a common pattern:
<?php
$nameErr = $emailErr = "";
$name = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = htmlspecialchars($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = filter_input(INPUT_POST, "email", FILTER_SANITIZE_EMAIL);
}
}
?>
πΉ 6. Displaying Form Data Back to the User
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Name: <input type="text" name="name" value="<?php echo $name; ?>">
<span style="color:red;"><?php echo $nameErr; ?></span><br>
Email: <input type="text" name="email" value="<?php echo $email; ?>">
<span style="color:red;"><?php echo $emailErr; ?></span><br>
<input type="submit" value="Submit">
</form>
<?php
if (!empty($name) && !empty($email)) {
echo "<h3>Welcome, $name ($email)!</h3>";
}
?>
β Output includes both the form and user feedback.
π§© Hands-On Practice
Exercise 1: Simple Form (form-basic.php)
<form method="POST" action="">
Enter your name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST['name']);
echo "<p>Hello, $name!</p>";
}
?>
β Input your name β it displays safely below the form.
Exercise 2: Email Validation (validate-email.php)
<form method="POST" action="">
Email: <input type="text" name="email">
<input type="submit" value="Check Email">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $_POST['email'];
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<p style='color:green;'>Valid email address</p>";
} else {
echo "<p style='color:red;'>Invalid email format</p>";
}
}
?>
Exercise 3: Required Fields (required.php)
<form method="POST" action="">
Name: <input type="text" name="name"><br>
Message: <textarea name="message"></textarea><br>
<input type="submit" value="Send">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"]) || empty($_POST["message"])) {
echo "<p style='color:red;'>All fields are required!</p>";
} else {
$name = htmlspecialchars($_POST["name"]);
$message = htmlspecialchars($_POST["message"]);
echo "<p>Thank you, $name. Your message has been received:</p>";
echo "<blockquote>$message</blockquote>";
}
}
?>
Exercise 4: Sanitization & Display (sanitize.php)
<form method="POST" action="">
Comment: <textarea name="comment"></textarea><br>
<input type="submit" value="Post Comment">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$comment = htmlspecialchars($_POST["comment"]);
echo "<h4>Your Safe Comment:</h4><p>$comment</p>";
}
?>
β
Test with <script> or HTML tags β PHP safely displays text instead of executing code.
π― Mini Project β Feedback Form with Validation (feedback.php)
<?php
$nameErr = $emailErr = "";
$name = $email = $feedback = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = htmlspecialchars($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = filter_input(INPUT_POST, "email", FILTER_SANITIZE_EMAIL);
}
if (!empty($_POST["feedback"])) {
$feedback = htmlspecialchars($_POST["feedback"]);
}
}
?>
<h2>Feedback Form</h2>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Name: <input type="text" name="name" value="<?php echo $name; ?>">
<span style="color:red;"><?php echo $nameErr; ?></span><br>
Email: <input type="text" name="email" value="<?php echo $email; ?>">
<span style="color:red;"><?php echo $emailErr; ?></span><br>
Feedback:<br>
<textarea name="feedback"><?php echo $feedback; ?></textarea><br>
<input type="submit" value="Submit">
</form>
<?php
if (!empty($name) && !empty($email)) {
echo "<h3>Thank you, $name!</h3>";
echo "<p>Weβve received your feedback:</p><blockquote>$feedback</blockquote>";
}
?>
β Output includes live error messages and sanitized feedback.
π§Ύ Module 7 Quiz
| # | Question | Options | Correct |
|---|---|---|---|
| 1 | Which PHP variable stores form data sent via POST? | a) $_FORM Β· b) $_POST Β· c) $_DATA | b |
| 2 | What function removes HTML tags? | a) sanitize_text() Β· b) htmlspecialchars() Β· c) strip_tags() | c |
| 3 | What will filter_var($email, FILTER_VALIDATE_EMAIL) return if invalid? |
a) false Β· b) true Β· c) null | a |
| 4 | Which method hides data from the URL? | a) GET Β· b) POST Β· c) BOTH | b |
| 5 | What is $_SERVER["REQUEST_METHOD"] used for? |
a) To display all form data Β· b) To detect submission type Β· c) To sanitize input | b |
πͺ Challenge Task β Contact Form with Error Handling and Success Message
Objective: Combine everything from this module to build a complete, safe form handling system
in contact-form.php.
- Name and Email fields (required)
- Message field (optional)
- Inline error messages
- Success message when submitted correctly
β Example output:
- Name is required.
- Email is required.
- β Thank you, Yogi! Your message has been received.
Make sure:
- You use
htmlspecialchars()andfilter_input() - The form re-populates values after submission
π§Ύ Submission Checklist
- β
form-basic.phpβ collects user input - β
validate-email.phpβ email validation works - β
required.phpβ error handling for empty fields - β
feedback.phpβ full validation and sanitization - β Quiz completed
π Next Step: In Module 8, youβll go deeper into file handling β learning how to save, read,
and display data from files using PHP. This forms the backbone of basic databases, logging systems, and even
CMS-like storage (before MySQL).