How can PHP be used to handle client-side input validation in a form submission process?
Client-side input validation can be handled using PHP by writing validation logic in the server-side script that processes the form submission. This way, even if a user bypasses client-side validation or submits the form without JavaScript enabled, the server-side validation will ensure that only valid data is accepted.
// Server-side validation example
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
// Validate name
if (empty($name)) {
$errors[] = "Name is required";
}
// Validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format";
}
// If there are errors, display them
if (!empty($errors)) {
foreach ($errors as $error) {
echo $error . "<br>";
}
} else {
// Process form submission
// Insert data into database, send email, etc.
}
}