EthicsComputerCourses
Join training +91 90532 10052

Secure Form Handling

HTML · Lesson 110 of 234 Advanced 11 min read Updated

By the end of this lesson you will be able to mark up a form so that browsers and password managers handle it safely, protect it against cross-site request forgery and bots, show errors that help users without helping attackers, and write a PHP handler that validates, stores and prints data safely.

What you should know first: HTML Forms Introduction (GET and POST), Native HTML Form Validation and HTML Security Fundamentals. Secure Authentication Form Design later goes deeper into login, password reset and two-factor forms.

A form is a door into your server

Anyone can send anything through a form, not only through your page but with tools like curl or a script. Your HTML shapes the experience for honest users; the server decides what gets in.

Keep one rule in mind for the whole lesson: the browser helps, the server decides. Attributes like required and maxlength are comfort for real users. An attacker skips them in one second.

HTTPS and POST: the basics, done properly

  • Serve the page and the action URL over HTTPS. HTTPS encrypts the data on its way, so nobody on the café Wi-Fi in Pune can read it. Browsers warn users when a secure page posts a form to an http:// address.
  • Use method="post" for anything sensitive or anything that changes data. GET puts values in the URL, and URLs end up in history, server logs, analytics and the Referer header.
  • Never put secrets in hidden fields. A hidden input is visible in the page source and easy to change.

CSRF: forged requests

Cross-site request forgery (CSRF) tricks a logged-in user's browser into sending a request they never meant to send. Suppose Rohan is logged into his college fee portal and visits a harmful page. A hidden form there posts to the portal's "change email" address. The browser attaches his session cookie, so the request looks genuine.

Think of a cheque. A forger can write a cheque in your name, but not on a leaf from your own chequebook. A CSRF token is that leaf: a long random value the server puts in its own form and remembers in the session. A form built on another site cannot know it.

PHP
<?php
// In the page that shows the form
$_SESSION['csrf_token'] ??= bin2hex(random_bytes(32));
?>
<form action="/register.php" method="post">
  <input type="hidden" name="csrf_token"
         value="<?= htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8') ?>">
  ...
</form>

The handler compares the submitted token with the session copy using hash_equals(), which takes the same time whether the first or the last character differs, and rejects the request if they do not match.

SameSite cookies add a second wall. The SameSite attribute tells the browser when to send a cookie with requests that start on another site:

ValueCookie sent on a cross-site POST?Good for
StrictNo, and not even when following a link from another siteBanking-style sessions
LaxNo, but yes for top-level link clicks (GET)Most login sessions
NoneYes (must also be Secure)Cookies that must work inside third-party embeds

Chrome and Edge treat a cookie with no SameSite attribute as Lax, but not every browser does, so always set it yourself. Use tokens and SameSite: tokens protect older browsers and same-site attacks, and SameSite catches the token you forgot. Servers can also check the Origin header or the newer Sec-Fetch-Site request header, which says whether a request came from the same site.

Autocomplete values that improve security

The autocomplete attribute tells the browser and password managers what each field is. Correct values make strong, unique passwords easy, which is a real security gain.

FieldValue
Login username or emailusername
Login passwordcurrent-password
New password on sign-up or changenew-password (password managers offer a strong one)
OTP from SMSone-time-code
Name, email, phonename, email, tel

Do not use autocomplete="off" to block password managers. Browsers usually ignore it on login fields anyway, and users who cannot paste or save passwords choose weaker ones. Password & Credential Autocomplete covers this in depth.

Bots: honeypots, rate limits and CAPTCHAs

Bots fill forms automatically to post spam, create fake accounts or guess passwords. Three tools slow them down:

  • A honeypot field is an extra input hidden from people but present in the HTML. Simple bots fill every input, so a filled honeypot marks a bot. Hide it off-screen with CSS, add aria-hidden="true" and tabindex="-1" so screen reader and keyboard users never meet it, and on the server pretend to succeed so the bot learns nothing.
  • Rate limiting counts attempts per account and per IP address, and slows or blocks them after a limit. The server answers 429 Too Many Requests, often with a Retry-After header.
  • CAPTCHAs are challenges that are easy for people and hard for bots. They also annoy and exclude people, especially users of screen readers. Use them only when the other layers are not enough, and pick one with an accessible option.

Step 1: a sign-up form with all the safe attributes

Here is a sign-up form for a Jaipur coaching centre. It posts to HTTPS, has a CSRF token, correct autocomplete values, limits that match the server and a honeypot. The demo stops the real submission and shows what would be sent.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Secure sign-up form</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; max-inline-size: 30rem; }
    label { display: block; margin-block-start: 10px; }
    input { inline-size: 100%; }
    .hp { position: absolute; left: -10000px; }
    pre { background: #f1f5f9; padding: 8px; white-space: pre-wrap; }
  </style>
</head>
<body>
  <h1>Jaipur Coaching Centre: sign up</h1>
  <form id="signup" action="https://www.example.com/register.php" method="post">
    <input type="hidden" name="csrf_token" value="9f2c41d8e7b05a63">

    <label for="name">Full name</label>
    <input id="name" name="name" autocomplete="name" required maxlength="80">

    <label for="email">Email</label>
    <input id="email" name="email" type="email" autocomplete="email" required>

    <label for="password">Password (12 to 72 characters)</label>
    <input id="password" name="password" type="password" autocomplete="new-password"
           required minlength="12" maxlength="72">

    <div class="hp" aria-hidden="true">
      <label for="website">Leave this empty</label>
      <input id="website" name="website" tabindex="-1" autocomplete="off">
    </div>

    <p><button>Create account</button> <button id="bot" type="button">Fill like a bot</button></p>
  </form>
  <pre id="sent" aria-live="polite"></pre>

  <script>
    const form = document.querySelector("#signup");
    document.querySelector("#bot").addEventListener("click", () => {
      // A simple bot fills every input it finds, including the hidden one
      for (const input of form.querySelectorAll("input:not([type=hidden])")) {
        input.value = input.type === "email" ? "bot@spam.example" : "buy-cheap-followers-now";
      }
      form.requestSubmit();
    });
    form.addEventListener("submit", (event) => {
      event.preventDefault(); // demo only: show what would be sent
      const lines = [];
      for (const [key, value] of new FormData(form)) {
        lines.push(key + " = " + (key === "password" ? "*".repeat(value.length) : value));
      }
      const trap = new FormData(form).get("website") !== "";
      lines.push(trap ? "Server: honeypot filled, so quietly drop it." : "Server: honeypot empty, so check the token and validate.");
      document.querySelector("#sent").textContent = lines.join("\n");
    });
  </script>
</body>
</html>

Submit the form yourself: website is sent empty. Click "Fill like a bot": the honeypot is filled, so the server would drop it. The real token would be a 64-character random value from the server, not a fixed string.

Errors that help users, not attackers

  • Login: say "Email or password is incorrect", never "No account with this email". Otherwise attackers can test which emails have accounts, called account enumeration.
  • Sign-up and password reset: give the same reply whether the email exists or not, and send the details by email.
  • Server errors: show a short, friendly message. Write the real error (SQL error, file path, stack trace) to a log file. Turn off PHP's display_errors on live servers.

Step 2: generic errors with a rate limit

This demo puts a pretend server inside the page so you can see the logic; in real life it runs on the server.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Login errors and rate limiting</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; max-inline-size: 28rem; }
    label { display: block; margin-block-start: 10px; }
    input { inline-size: 100%; }
    #message { color: #b91c1c; min-block-size: 1.5em; }
  </style>
</head>
<body>
  <h1>Student portal login</h1>
  <p>Test account: meera@example.com / rohtak-library-2026</p>
  <form id="login">
    <label for="email">Email</label>
    <input id="email" name="email" type="email" autocomplete="username" required>
    <label for="password">Password</label>
    <input id="password" name="password" type="password" autocomplete="current-password" required>
    <p><button>Log in</button></p>
  </form>
  <p id="message" aria-live="polite"></p>

  <script>
    // ---- Pretend server: in real life this runs in PHP, not in the browser ----
    const accounts = { "meera@example.com": "rohtak-library-2026" };
    const failures = new Map(); // email -> { count, lockedUntil }
    function serverLogin(email, password) {
      const now = Date.now();
      const record = failures.get(email) || { count: 0, lockedUntil: 0 };
      if (record.lockedUntil > now) {
        return { status: 429, wait: Math.ceil((record.lockedUntil - now) / 1000) };
      }
      if (accounts[email] === password) {
        failures.delete(email);
        return { status: 200 };
      }
      record.count++;
      if (record.count >= 3) {           // third failure: lock for 30 seconds
        record.lockedUntil = now + 30000;
        record.count = 0;
      }
      failures.set(email, record);
      return { status: 401 };            // same answer for wrong email or wrong password
    }
    // ---- Page code ----
    const form = document.querySelector("#login");
    const message = document.querySelector("#message");
    form.addEventListener("submit", (event) => {
      event.preventDefault();
      const result = serverLogin(form.email.value.trim().toLowerCase(), form.password.value);
      if (result.status === 200) {
        message.style.color = "#166534";
        message.textContent = "Welcome back!";
      } else if (result.status === 429) {
        message.style.color = "";
        message.textContent = "Too many attempts. Try again in " + result.wait + " seconds.";
      } else {
        message.style.color = "";
        message.textContent = "Email or password is incorrect.";
        form.password.value = "";
      }
    });
  </script>
</body>
</html>

Try an unknown email, then a wrong password for Meera: both give the same message. After three wrong passwords, even the correct one must wait 30 seconds. The aria-live region makes screen readers announce each message.

File uploads

Uploads are the riskiest form field, because the user sends you a whole file. The accept attribute only filters the file picker; it is not a check. On the server:

  • Check the upload error code and a maximum size.
  • Detect the real type from the file's contents with finfo, never from the file name or the browser's claimed type.
  • Allow a short list of types, and pick the extension yourself from the detected type.
  • Give the file a new random name and store it outside the public web folder, so it can never run as code.
PHP
$allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'application/pdf' => 'pdf'];
$file = $_FILES['document'];
if ($file['error'] !== UPLOAD_ERR_OK || $file['size'] > 2_000_000) {
    exit('Please upload a file under 2 MB.');
}
$type = (new finfo(FILEINFO_MIME_TYPE))->file($file['tmp_name']);
if (!isset($allowed[$type])) {
    exit('Only JPG, PNG or PDF files are allowed.');
}
$newName = bin2hex(random_bytes(16)) . '.' . $allowed[$type];
move_uploaded_file($file['tmp_name'], '/var/app-uploads/' . $newName);

A file called marks.php.jpg gets a random name ending in the extension you chose. File Uploads in the PHP course covers the full process.

Putting it together: a PHP handler

Here is a complete sign-up handler. It runs the checks in a sensible order: method, CSRF token, honeypot, validation, then storage.

PHP
<?php
declare(strict_types=1);

session_start([
    'cookie_secure'   => true,   // only over HTTPS
    'cookie_httponly' => true,   // JavaScript cannot read it
    'cookie_samesite' => 'Lax',  // not sent on cross-site POSTs
]);

function e(string $text): string
{
    return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function finish(int $status, string $message): never
{
    http_response_code($status);
    echo '<p>' . e($message) . '</p>';
    exit;
}

// 1. Only POST, and only with the CSRF token from our own form
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    finish(405, 'Please use the sign-up form.');
}
$token = $_POST['csrf_token'] ?? '';
if (!is_string($token) || !hash_equals($_SESSION['csrf_token'] ?? '', $token)) {
    finish(403, 'Your session has expired. Please reload the form and try again.');
}

// 2. Honeypot: people never see this field, many bots fill it
if (($_POST['website'] ?? '') !== '') {
    finish(200, 'Thank you. Please check your email.');
}

// 3. Validate every field again, whatever the browser checked
$name     = trim((string) ($_POST['name'] ?? ''));
$email    = trim((string) ($_POST['email'] ?? ''));
$password = (string) ($_POST['password'] ?? '');
$errors   = [];
if ($name === '' || mb_strlen($name) > 80) {
    $errors[] = 'Enter your name (up to 80 characters).';
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
    $errors[] = 'Enter a valid email address.';
}
if (mb_strlen($password) < 12 || strlen($password) > 72) {
    $errors[] = 'Use a password of 12 to 72 characters.';
}
if ($errors) {
    http_response_code(422);
    foreach ($errors as $error) {
        echo '<p>' . e($error) . '</p>';
    }
    exit;
}

// 4. Store it: prepared statement, hashed password
$pdo = new PDO(
    'mysql:host=localhost;dbname=school;charset=utf8mb4',
    'school_app',
    getenv('DB_PASSWORD') ?: '',
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
$stmt = $pdo->prepare('INSERT INTO users (name, email, password_hash) VALUES (?, ?, ?)');
try {
    $stmt->execute([$name, $email, password_hash($password, PASSWORD_DEFAULT)]);
} catch (PDOException $ex) {
    if ($ex->getCode() !== '23000') {   // 23000: email already registered
        error_log($ex->getMessage());   // details go to the log, never the page
        finish(500, 'Something went wrong. Please try again later.');
    }
}

// 5. Same reply for new and existing emails, so nobody can test who has an account
finish(200, 'Thank you, ' . $name . '. Please check your email to confirm your account.');

We ran this handler with PHP 8.4, using SQLite in place of MySQL, for five requests. A first sign-up named Isha <b>Verma</b> and the same sign-up again both returned:

Output
<p>Thank you, Isha &lt;b&gt;Verma&lt;/b&gt;. Please check your email to confirm your account.</p>

A wrong token gave status 403, a filled honeypot gave the friendly 200 reply, and a bad email with the password short gave status 422 with two messages. The name was stored as typed but printed as harmless text.

Points to notice:

  • Prepared statements send the SQL and the values separately, so input can never change the query (SQL injection).
  • password_hash() with PASSWORD_DEFAULT uses bcrypt (cost 12 in PHP 8.4) with a random salt. Bcrypt only reads the first 72 bytes, which is why the handler limits the length.
  • htmlspecialchars() on output turns < into &lt;, so stored text cannot become HTML.
  • In production, an existing user should get an email saying "someone tried to sign up with your address".

Common mistakes

  • Trusting browser validation. Every check must run again on the server.
  • POST without a CSRF token, or relying on SameSite alone.
  • Error messages that reveal accounts, SQL or file paths.
  • Hiding a honeypot with type="hidden". Bots skip hidden inputs; hide it with CSS instead.
  • Saving uploads with the user's file name inside the public folder.
  • autocomplete="off" on passwords. It pushes users towards weak passwords.

Interview questions

1. What is CSRF and how do you prevent it?

CSRF makes a logged-in user's browser send a request they did not intend, using their cookies. Prevent it with a random per-session token in every state-changing form, checked on the server with a constant-time comparison. Add SameSite=Lax or Strict session cookies and, optionally, Origin or Sec-Fetch-Site checks.

2. Why validate on the server if the browser already validates?

Browser validation is only for user comfort. Anyone can send a request with curl, edit the HTML in DevTools or disable JavaScript. Only server-side checks are actually enforced.

3. What is a honeypot field?

An extra input that people never see but simple bots fill. If it arrives with a value, the server silently drops the request while pretending success. Hide it with CSS rather than type="hidden", and keep it away from keyboard and screen reader users.

4. How should a login form report a failed attempt?

With one generic message such as "Email or password is incorrect", so attackers cannot learn which emails are registered. Combine it with rate limiting per account and per IP, answering 429 Too Many Requests when the limit is reached.

5. Which autocomplete values matter for security?

username and current-password on login, new-password on sign-up and password change, and one-time-code for OTPs. They let password managers fill and generate strong passwords. Blocking autofill usually makes passwords weaker.

Key points

  • The browser helps, the server decides: repeat every check on the server.
  • Use HTTPS everywhere and POST for sensitive or data-changing forms; hidden fields are not secret.
  • Stop CSRF with tokens checked by hash_equals(), plus SameSite session cookies.
  • Correct autocomplete values help password managers and strengthen passwords.
  • Slow bots with honeypots and rate limits; use CAPTCHAs sparingly and accessibly.
  • Check uploads by content, rename them randomly and store them outside the web root.
  • In PHP: prepared statements, password_hash(), htmlspecialchars() on output, and generic error messages.

Exercise

Write a "Change email" form and its PHP handler for a student portal in Kochi. The form needs the new email (with the right type and autocomplete), the current password (autocomplete="current-password"), a CSRF token and a honeypot. The handler must check the method, the token and the honeypot, validate the email, verify the password with password_verify() against the user's stored hash, update the row with a prepared statement and reply with a generic message on failure.

Show solution
PHP
<?php
declare(strict_types=1);
session_start(['cookie_secure' => true, 'cookie_httponly' => true, 'cookie_samesite' => 'Lax']);

$userId = $_SESSION['user_id'] ?? null;
$token  = $_POST['csrf_token'] ?? '';
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || $userId === null
    || !is_string($token) || !hash_equals($_SESSION['csrf_token'] ?? '', $token)) {
    http_response_code(403);
    exit('Please reload the page and try again.');
}
if (($_POST['website'] ?? '') !== '') {
    exit('Done.');
}
$email = trim((string) ($_POST['email'] ?? ''));
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
    http_response_code(422);
    exit('Enter a valid email address.');
}

$pdo = new PDO('mysql:host=localhost;dbname=school;charset=utf8mb4', 'school_app',
    getenv('DB_PASSWORD') ?: '', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$stmt = $pdo->prepare('SELECT password_hash FROM users WHERE id = ?');
$stmt->execute([$userId]);
$hash = $stmt->fetchColumn();
if ($hash === false || !password_verify((string) ($_POST['password'] ?? ''), $hash)) {
    http_response_code(401);
    exit('That did not work. Check your password and try again.');
}
$pdo->prepare('UPDATE users SET email = ? WHERE id = ?')->execute([$email, $userId]);
echo 'Your email has been updated.';
HTML
<form action="/change-email.php" method="post">
  <input type="hidden" name="csrf_token" value="TOKEN_FROM_SESSION">
  <label for="email">New email</label>
  <input id="email" name="email" type="email" autocomplete="email" required>
  <label for="password">Current password</label>
  <input id="password" name="password" type="password" autocomplete="current-password" required>
  <div class="hp" aria-hidden="true">
    <label for="website">Leave this empty</label>
    <input id="website" name="website" tabindex="-1" autocomplete="off">
  </div>
  <button>Change email</button>
</form>

Asking for the current password means a stolen session alone cannot change the email. A real portal would also email the old address about the change and rate-limit wrong passwords.

Quick Quiz

1. Which cookie setting stops the session cookie being sent on a POST from another site?

2. Why does a honeypot input use CSS to hide it instead of type="hidden"?

3. What should a login form say when the email does not exist?

4. How should the server decide an uploaded file's type?

Learn HTML with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call