iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP Form Handling

Forms are the most common reason a browser sends data back to PHP. The same script usually shows the form on GET, processes it on POST.

HTML side

HTML
<form action="contact.php" method="post">
    <label>Name <input name="name"></label>
    <label>Email <input type="email" name="email"></label>
    <button type="submit">Send</button>
</form>

PHP side — POST

PHP — contact.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name  = trim($_POST['name']  ?? '');
    $email = trim($_POST['email'] ?? '');
    echo 'Hello, ' . htmlspecialchars($name);
}

GET vs POST

GETPOST
Data lives inURL query stringRequest body
Visible in URLYesNo
Cacheable / bookmarkableYesNo
Use forIdempotent reads (search, filters)Side effects (creates, deletes)
Size limits~2 KB (URL)Big — depends on server config

POST → redirect → GET

After a successful POST, redirect to a GET URL. This stops the browser from re-submitting the form when the user refreshes:

PHP
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // … save data …
    header('Location: /thanks');
    exit;
}

CSRF protection

Anyone can craft a hidden form on another site that POSTs to yours. The fix: include a per-session token, check it on submit. Frameworks do this automatically with @csrf / {% csrf_token %}.

Tip: Always escape user input on the way out (htmlspecialchars for HTML, parameter binding for SQL). Don't try to "clean" it on the way in — meaning depends on context.

Example

Example
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    echo 'Hello, ' . htmlspecialchars($name);
} else {
    echo '<form method="post">Name: <input name="name"><button>Send</button></form>';
}
Try it Yourself »

Exercise

Check the request method.

$ _['REQUEST_METHOD'] === 'POST'

Test yourself

Q1. After successful POST, best practice is to…
Q2. For uploads, the form must use…
Q3. CSRF defence is typically a…

Discussion

Loading…