Data security is the most critical part of form handling. You should never trust user input. Hackers can use forms to inject malicious scripts (XSS) or database commands. Validation ensures your data is clean, correct, and safe.
To keep your code organized, create a function that cleans every piece of input before you use it.
<?php
function test_input($data) {
$data = trim($data); // Removes extra spaces/newlines
$data = stripslashes($data); // Removes backslashes
$data = htmlspecialchars($data);// Converts special chars to HTML entities
return $data;
}
?>
You can check if a field is empty before processing. If it is, display an error message to the user.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
}
?>
PHP provides filter_var() for advanced validation like emails and URLs.
<?php
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
?>
<?php
$website = test_input($_POST["website"]);
if (!filter_var($website, FILTER_VALIDATE_URL)) {
$websiteErr = "Invalid URL";
}
?>
htmlspecialchars()? It converts characters like < and > into < and >. This prevents browsers from executing a script tag if a user tries to inject one.
required) is great for UX, but server-side validation in PHP is mandatory for security.
htmlspecialchars() to prevent XSS attacks.trim() and stripslashes() to clean up unnecessary characters.empty() function checks for required data.filter_var() for structured data like Email and URLs.