πŸ“– Validating Form Input in a PHP Controller

πŸ“ Where You Left Off

  • register.php calls UserController::register()
  • register() loads views/profile/create.php
  • The form includes fields for name and email

βš™οΈ Update the Controller for Form Handling

In your controller file, add validation logic inside the register() method. This version distinguishes between GET and POST requests:

<?php
class UserController {
    public function register() {
        $post = ['name' => '', 'email' => ''];
        $errors = [];

        // Check if the request is POST
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $post['name'] = trim($_POST['name'] ?? '');
            $post['email'] = trim($_POST['email'] ?? '');

            // Validate required fields
            if ($post['name'] === '') {
                $errors['name'] = 'Name is required.';
            }

            // Validate email format
            if (!filter_var($post['email'], FILTER_VALIDATE_EMAIL)) {
                $errors['email'] = 'Please enter a valid email address.';
            }
        }

        require 'views/profile/create.php'; // Always Load the view
    }
}

This logic runs on every request. If the method is POST, it sanitizes the input and collects error messages. These are passed to the view using the $post and $errors arrays. If there is no POST request, the view loads a blank form.

πŸ–ΌοΈ Update the View with Sticky Fields and Errors

Edit views/profile/create.php to show validation feedback and preserve submitted input:

<?php include 'views/partials/header.php'; ?>

<h2>Create Profile</h2>

  <form method="POST" action="register.php">
    <div>
      <label for="name">Name</label>
      <input id="name" name="name" value="<?= htmlspecialchars($post['name'] ?? '') ?>">
      <?php if (!empty($errors['name'])): ?>
        <p class="text-danger"><?= htmlspecialchars($errors['name']) ?></p>
      <?php endif; ?>
    </div>

    <div>
      <label for="email">Email</label>
      <input id="email" name="email" value="<?= htmlspecialchars($post['email'] ?? '') ?>">
      <?php if (!empty($errors['email'])): ?>
        <p class="text-danger"><?= htmlspecialchars($errors['email']) ?></p>
      <?php endif; ?>
    </div>

    <button type="submit">Register</button>
  </form>

<?php include 'views/partials/footer.php'; ?>

This view does three important things:

  • It uses the $post array to prefill user-entered values
  • It checks the $errors array to display specific messages
  • It uses htmlspecialchars() to prevent cross-site scripting (XSS)

βœ… Recap

  • The controller now checks for valid input before displaying the form
  • The form provides user feedback for each required field
  • Input is preserved so users don’t lose their work

πŸ’‘ Next Step: Write the valid data to a MySQL database using a secure model function.

Last updated: August 8, 2025 at 1:27 PM