PHP Form Complete
PHP Form Handling: Validation and Repopulation
Section titled “PHP Form Handling: Validation and Repopulation”A common requirement in web development is processing HTML forms. This involves validating user input on the server-side and repopulating the form with previously entered values if validation fails, improving user experience.
PHP - Repopulating Form Fields
Section titled “PHP - Repopulating Form Fields”To show the values in the input fields after the user submits the form (especially if there are errors), we need to embed PHP code within the HTML form elements.
For text inputs, textareas, and select dropdowns, set the value attribute (or the content for <textarea>) to the submitted value. For radio buttons and checkboxes, dynamically add the checked attribute if the submitted value matches the button’s/checkbox’s value.
Crucial Security Note: Always escape user-provided data before outputting it back into HTML to prevent Cross-Site Scripting (XSS) attacks. Use the htmlspecialchars() function.
Example Snippets:
<!-- Name Input --><label for="name">Name:</label><input type="text" id="name" name="name" value="<?= htmlspecialchars($_POST['name'] ?? '') ?>">
<!-- Email Input --><label for="email">E-mail:</label><input type="text" id="email" name="email" value="<?= htmlspecialchars($_POST['email'] ?? '') ?>">
<!-- Website Input --><label for="website">Website:</label><input type="text" id="website" name="website" value="<?= htmlspecialchars($_POST['website'] ?? '') ?>">
<!-- Comment Textarea --><label for="comment">Comment:</label><textarea id="comment" name="comment" rows="5" cols="40"><?= htmlspecialchars($_POST['comment'] ?? '') ?></textarea>
<!-- Gender Radio Buttons --><fieldset> <legend>Gender:</legend> <input type="radio" id="female" name="gender" value="female" <?= (($_POST['gender'] ?? '') === 'female') ? 'checked' : '' ?>> <label for="female">Female</label> <input type="radio" id="male" name="gender" value="male" <?= (($_POST['gender'] ?? '') === 'male') ? 'checked' : '' ?>> <label for="male">Male</label></fieldset>
<!-- Note: The `?? ''` (Null Coalescing Operator) provides an empty default value if the POST variable isn't set, preventing errors on the initial page load. -->PHP - Complete Form Validation Example
Section titled “PHP - Complete Form Validation Example”Here is a complete example demonstrating server-side validation and form repopulation using modern PHP practices.
<?php
// Initialize variables for errors and submitted data$errors = [];$formData = [ 'name' => '', 'email' => '', 'website' => '', 'comment' => '', 'gender' => ''];
// --- Form Processing Logic ---if ($_SERVER["REQUEST_METHOD"] === "POST") {
// Basic Sanitization (trim whitespace) $formData['name'] = trim($_POST['name'] ?? ''); $formData['email'] = trim($_POST['email'] ?? ''); $formData['website'] = trim($_POST['website'] ?? ''); $formData['comment'] = trim($_POST['comment'] ?? ''); $formData['gender'] = $_POST['gender'] ?? ''; // No trim for radio/select
// --- Validation Rules ---
// Name Validation if (empty($formData['name'])) { $errors['name'] = "Name is required"; } elseif (!preg_match("/^[a-zA-Z-' ]*$/", $formData['name'])) { // Allow letters, whitespace, hyphens, apostrophes $errors['name'] = "Only letters, hyphens, apostrophes and white space allowed"; }
// Email Validation if (empty($formData['email'])) { $errors['email'] = "Email is required"; } elseif (!filter_var($formData['email'], FILTER_VALIDATE_EMAIL)) { $errors['email'] = "Invalid email format"; }
// Website Validation (Optional Field) if (!empty($formData['website'])) { // Use filter_var for robust URL validation if (!filter_var($formData['website'], FILTER_VALIDATE_URL)) { $errors['website'] = "Invalid URL format"; } }
// Comment Validation (Optional - example: check length if needed) // if (!empty($formData['comment']) && strlen($formData['comment']) > 500) { // $errors['comment'] = "Comment cannot exceed 500 characters"; // }
// Gender Validation if (empty($formData['gender'])) { $errors['gender'] = "Gender is required"; } elseif (!in_array($formData['gender'], ['female', 'male'])) { // Validate against expected values $errors['gender'] = "Invalid gender selected"; }
// --- Check if Validation Passed --- if (empty($errors)) { // Process the valid data (e.g., save to database, send email) // ... echo "<p style='color:green;'>Form submitted successfully!</p>"; // Optionally redirect or clear form data // header('Location: thank_you.php'); // exit; } else { echo "<p style='color:red;'>Please fix the errors below.</p>"; }}
?>
<!DOCTYPE html><html><head> <title>PHP Form Example</title> <style> .error { color: #FF0000; } label { display: block; margin-top: 10px; } input[type=text], textarea { width: 300px; } fieldset { border: 1px solid #ccc; padding: 10px; margin-top: 10px; width: 300px; } legend { font-weight: bold; } </style></head><body>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?= htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<label for="name">Name:</label> <input type="text" id="name" name="name" value="<?= htmlspecialchars($formData['name']) ?>"> <span class="error"><?= $errors['name'] ?? '' ?></span>
<label for="email">E-mail:</label> <input type="text" id="email" name="email" value="<?= htmlspecialchars($formData['email']) ?>"> <span class="error"><?= $errors['email'] ?? '' ?></span>
<label for="website">Website:</label> <input type="text" id="website" name="website" value="<?= htmlspecialchars($formData['website']) ?>"> <span class="error"><?= $errors['website'] ?? '' ?></span>
<label for="comment">Comment:</label> <textarea id="comment" name="comment" rows="5" cols="40"><?= htmlspecialchars($formData['comment']) ?></textarea> <span class="error"><?= $errors['comment'] ?? '' ?></span>
<fieldset> <legend>Gender:</legend> <input type="radio" id="female" name="gender" value="female" <?= ($formData['gender'] === 'female') ? 'checked' : '' ?>> <label for="female" style="display:inline;">Female</label> <input type="radio" id="male" name="gender" value="male" <?= ($formData['gender'] === 'male') ? 'checked' : '' ?>> <label for="male" style="display:inline;">Male</label> <br><span class="error"><?= $errors['gender'] ?? '' ?></span> </fieldset>
<br><br> <input type="submit" name="submit" value="Submit">
</form>
</body></html>Further Considerations:
Section titled “Further Considerations:”- CSRF Protection: Real-world applications must implement Cross-Site Request Forgery (CSRF) protection, typically using tokens. This example omits it for simplicity.
- Sanitization vs. Validation: Validation checks if data is in the correct format. Sanitization cleans or modifies data (e.g.,
trim(),htmlspecialchars()for output, or removing potentially harmful code before database storage). Apply them appropriately. - Error Display: The example shows errors next to fields. You might prefer a summary list at the top or other UI approaches.
- Frameworks: Modern PHP frameworks (like Laravel, Symfony) provide robust components for form handling, validation, and security, significantly simplifying this process.