Process an HTML Form Securely with PHP

Last updated: August 26, 2026.

Submit forms with POST, validate every field on the server, protect state-changing requests against CSRF, and encode values when displaying them.

HTML form

<form method="post" action="contact.php">
  <label for="email">Email</label>
  <input id="email" name="email" type="email" required>
  <label for="message">Message</label>
  <textarea id="message" name="message" required></textarea>
  <button type="submit">Send</button>
</form>

PHP handler

<?php
declare(strict_types=1);

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit;
}

$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$message = trim((string) ($_POST['message'] ?? ''));
if ($email === false || $message === '' || mb_strlen($message) > 5000) {
    http_response_code(422);
    exit('Please correct the form.');
}

// Store with a prepared statement or pass to a trusted mail service.

Add a session-bound CSRF token, rate limiting, and a Post/Redirect/Get response in production. Browser validation improves usability but does not replace server validation.

admin

admin

Leave a Reply

Your email address will not be published.