Skip to content

PHP Tutorial Forms and User Input

HTML Forms with PHP

Lesson 134 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

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:

  1. HTML draws the fields and the Submit button.
  2. PHP receives what the visitor typed and decides what to do.

The journey of a form

  1. The visitor fills in the fields and presses Submit.
  2. The browser sends the values to the address in the form’s action, using the method you chose (get or post).
  3. The server runs your PHP file.
  4. PHP reads the values from $_GET or $_POST.
  5. PHP validates them, does the work (save, send, search) and returns a page.

A first form

Save this as hello.php:

index.php
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

AttributeWhat it does
actionThe URL that receives the data. Empty or missing means the same page
methodget 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.

index.html
HTML
<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).

info
This course page cannot run the form
PHP needs a server, so run this example on your own machine. Running Your First PHP File shows how.