PHP Forms - Required Fields

In PHP, making form fields required is a common task to ensure users provide necessary information before submitting the form. Here's a step-by-step guide to handling required fields in a PHP form:


1. HTML Form with Required Fields

You can use the required attribute in HTML to enforce input on the client side.

<form action="process.php" method="POST"> Name: <input type="text" name="name" required><br> Email: <input type="email" name="email" required><br> <input type="submit" value="Submit"> </form>

2. PHP Backend Validation (Server-side)

Always validate data on the server as well, even if the client does.

process.php example:

<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { $errors = []; // Trim and validate inputs $name = trim($_POST["name"] ?? ''); $email = trim($_POST["email"] ?? ''); if (empty($name)) { $errors[] = "Name is required."; } if (empty($email)) { $errors[] = "Email is required."; } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Invalid email format."; } if (empty($errors)) { // Process data, e.g., save to DB or send email echo "Form submitted successfully!"; } else { // Display errors foreach ($errors as $error) { echo "<p style='color:red;'>$error</p>"; } } } ?>