What are best practices for handling form validation in PHP to ensure accurate user input?
When handling form validation in PHP, it is important to thoroughly validate user input to ensure data accuracy and security. Best practices include using server-side validation to prevent malicious input, sanitizing input data to prevent SQL injection attacks, and providing clear error messages to guide users in correcting their input.
<?php
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate input fields
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
// Validate name
if (empty($name)) {
$nameErr = "Name is required";
} else {
// Check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
// Validate email
if (empty($email)) {
$emailErr = "Email is required";
} else {
// Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
}
// Function to sanitize input data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>