Form validation ensures that user input matches required data formats, character limits, and constraints before saving to a database or executing application logic. Sanitization strips unwanted HTML markup and malicious characters to prevent Cross-Site Scripting (XSS) attacks.
htmlspecialchars(), strip_tags()).flowchart TD
A["Raw User Input ($_POST / $_GET)"] --> B["Trim Whitespace: trim()"]
B --> C["Strip Unsafe Markup: htmlspecialchars()"]
C --> D{"Validate Format Constraints"}
D -- Pass --> E["Proceed with Business Logic"]
D -- Fail --> F["Return User Errors Array"]
<?php
declare(strict_types=1);
function sanitizeInput(string $data): string
{
$data = trim($data);
$data = stripslashes($data);
return htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
}
$errors = [];
$formData = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 1. Process & Sanitize Full Name
$rawName = $_POST['name'] ?? '';
$cleanName = sanitizeInput($rawName);
if (empty($cleanName)) {
$errors['name'] = "Name field cannot be left blank.";
} else {
$formData['name'] = $cleanName;
}
// 2. Process & Validate Age
$rawAge = $_POST['age'] ?? '';
if (!filter_var($rawAge, FILTER_VALIDATE_INT, ["options" => ["min_range" => 18, "max_range" => 100]])) {
$errors['age'] = "Age must be a valid integer between 18 and 100.";
} else {
$formData['age'] = (int)$rawAge;
}
}
htmlspecialchars($str, ENT_QUOTES, 'UTF-8'): Converts both single and double quotes to HTML entities preventing script injection.Write a sanitization function cleanField(string $input): string that trims whitespace, removes slashes, and escapes HTML special characters!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.