PHP Form Validation

Form validation in PHP typically involves checking user input for correctness and completeness before it is processed or stored. Here's a basic example of PHP form validation that checks for required fields, validates email format, and sanitizes input.


HTML Form (form.html)

<!DOCTYPE html> <html> <head> <title>PHP Form Validation</title> </head> <body> <h2>Simple Form</h2> <form method="post" action="form-handler.php"> Name: <input type="text" name="name"><br><br> Email: <input type="text" name="email"><br><br> Message: <textarea name="message"></textarea><br><br> <input type="submit" value="Submit"> </form> </body> </html>

PHP Form Handler (form-handler.php)

<?php // Define variables and set to empty values $name = $email = $message = ""; $nameErr = $emailErr = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { // Sanitize input function clean_input($data) { return htmlspecialchars(stripslashes(trim($data))); } // Validate name if (empty($_POST["name"])) { $nameErr = "Name is required"; } else { $name = clean_input($_POST["name"]); } // Validate email if (empty($_POST["email"])) { $emailErr = "Email is required"; } else { $email = clean_input($_POST["email"]); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; } } // Optional message if (!empty($_POST["message"])) { $message = clean_input($_POST["message"]); } // Output or handle form data if (empty($nameErr) && empty($emailErr)) { echo "<h3>Form Submitted Successfully!</h3>"; echo "Name: $name<br>"; echo "Email: $email<br>"; echo "Message: $message<br>"; } else { echo "<h3>Form Validation Errors</h3>"; echo $nameErr . "<br>" . $emailErr; } } ?>

Key Points:

  • Always validate and sanitize user input.

  • Use filter_var() for common formats like emails.

  • htmlspecialchars() protects against XSS.

  • Server-side validation is crucial even if you use JavaScript on the client.