Forms are how visitors talk to your server. A search box, a login, a comment, a checkout: all are forms.
A form works in two halves:
- HTML draws the fields and the Submit button.
- PHP receives what the visitor typed and decides what to do.
The journey of a form
- The visitor fills in the fields and presses Submit.
- The browser sends the values to the address in the form’s
action, using themethodyou chose (getorpost). - The server runs your PHP file.
- PHP reads the values from
$_GETor$_POST. - PHP validates them, does the work (save, send, search) and returns a page.
A first form
Save this as hello.php:
<form action="hello.php" method="post">
<label for="name">Your name</label>
<input type="text" id="name" name="name">
<button type="submit">Say hello</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = trim($_POST["name"] ?? "");
echo "<p>Hello, " . htmlspecialchars($name) . "!</p>";
}
When the page first loads, it is a normal request (GET), so only the form shows. After the visitor submits, the browser sends a POST request to the same file. The if runs, and PHP prints the greeting.
The important attributes
| Attribute | What it does |
|---|---|
action | The URL that receives the data. Empty or missing means the same page |
method | get puts data in the URL, post sends it in the request body |
name (on each field) | The key PHP uses to read the value |
The name attribute matters most. A field without name is not sent at all.
<input type="text" name="email"> <!-- PHP reads $_POST["email"] -->
<input type="text" id="email"> <!-- NOT sent: no name -->
Always label your fields
Every field needs a <label> linked with for and id. It helps screen reader users and gives a bigger click area. See the HTML forms lessons.
The golden rule
Everything in $_GET and $_POST comes from the visitor. They can send anything, in any shape, even without using your form. Treat all of it as untrusted until you have validated it, and escape it when you print it back (see Output Escaping).