PHP
Challenge - Secure feedback form
Build a secure feedback form with an HTML form, $_POST and htmlspecialchars.
Challenge - Secure feedback form
In this challenge you'll write a function that processes a feedback form. The processFeedback(array $data): string function validates the name and message from the form and prepares them for safe output.
If a field is empty you return an error message. For filled fields you escape them with htmlspecialchars to prevent XSS. This combines form validation and output security.
$_POST and htmlspecialchars refresher
You read form data from the $_POST superglobal; each field is a key. A user may enter dangerous text like <script>; before printing it you escape it with htmlspecialchars.
To check for empty fields you compare with === ""; with ?? you give a default for missing keys. In this challenge processFeedback will do both validation and escaping.
Exercise Write the secure feedback handler
Define processFeedback(array $data): string. Get the values with $name = $data["name"] ?? "" and $message = $data["message"] ?? "". If either is === "", return "Error: name and message required". Otherwise escape both with htmlspecialchars($name, ENT_QUOTES, "UTF-8") and return $safeName . ": " . $safeMessage. Then add three echo calls: ["name" => "Alex", "message" => "Great"], ["name" => "<b>", "message" => "hi"] and ["name" => "", "message" => ""]; append "\n" to each line.
Show example solution
Use $data["name"] ?? "" for a default on missing keys; check emptiness with === ""; escape with htmlspecialchars($name, ENT_QUOTES, "UTF-8").
Example solution:
<?php
// Write processFeedback
function processFeedback(array $data): string {
$name = $data["name"] ?? "";
$message = $data["message"] ?? "";
if ($name === "" || $message === "") {
return "Error: name and message required";
}
$safeName = htmlspecialchars($name, ENT_QUOTES, "UTF-8");
$safeMessage = htmlspecialchars($message, ENT_QUOTES, "UTF-8");
return $safeName . ": " . $safeMessage;
}
echo processFeedback(["name" => "Alex", "message" => "Great"]) . "\n";
echo processFeedback(["name" => "<b>", "message" => "hi"]) . "\n";
echo processFeedback(["name" => "", "message" => ""]) . "\n";
Test yourself
-
What is htmlspecialchars for?
- Escapes HTML special characters, preventing XSS
- Stores form data in a database
- Auto-fills form fields
- Deletes empty fields
Show answer
Escapes HTML special characters, preventing XSS — Correct. htmlspecialchars turns <, > and quotes into HTML entities, preventing XSS attacks.
-
Complete the htmlspecialchars call
$safe = htmlspecialchars($name, ____, "UTF-8");
Show answer
$safe = htmlspecialchars($name, ENT_QUOTES, "UTF-8");
-
Match the form concepts
- $_POST
- form data
- htmlspecialchars
- XSS protection
- null coalesce
- default value
- validation
- empty field check
Next lesson: Challenge - Array operations