CodeBlanks Logo Icon CodeBlanks

Processing form data

PHP course · Beginner · Lesson 101/116

Learn to receive POST-submitted form data through $_POST.

Reading data with $_POST

When a form is sent with method="post", PHP gathers the fields in the $_POST superglobal. A field with name="email" shows up on the PHP side as $_POST['email']. To learn whether the form was submitted, you check the submit button name or $_SERVER['REQUEST_METHOD'].

Example: if ($_SERVER['REQUEST_METHOD'] === 'POST') { $name = $_POST['name'] ?? ''; echo "Hello " . $name; }. The ?? gives an empty string for a missing key, so the page does not error when opened before submission.

Detecting submission

A form page both shows the form and processes the data when it is submitted. To tell that the form was sent there are two common ways: check the submit button name with isset(), or read $_SERVER['REQUEST_METHOD'].

The second way is more robust: if ($_SERVER['REQUEST_METHOD'] === 'POST') { ... }. When this condition is true you read the form data; otherwise you only show the form. For CLI testing you can set $_SERVER['REQUEST_METHOD'] = 'POST'; by hand.

Exercise Receive form data with $_POST and print it

Set $_SERVER['REQUEST_METHOD'] = "POST";. Set $_POST['name'] = "Alex";. Inside if ($_SERVER['REQUEST_METHOD'] === "POST") write echo "Hello, " . $_POST['name'] . "!";.

Show example solution
First write $_SERVER['REQUEST_METHOD'] = "POST"; and $_POST['name'] = "Alex";. Then add if ($_SERVER['REQUEST_METHOD'] === "POST") { echo "Hello, " . $_POST['name'] . "!"; }.
Example solution:
<?php
// Receive form data with $_POST and print it
$_SERVER['REQUEST_METHOD'] = "POST";
$_POST['name'] = "Alex";
if ($_SERVER['REQUEST_METHOD'] === "POST") {
    echo "Hello, " . $_POST['name'] . "!";
}

Test yourself

  1. Read the name field from $_POST

    $name = ____['name'] ?? "";
    Show answer
    $name = $_POST['name'] ?? "";
  2. What is the most robust way to tell the form was submitted?

    • Check if $_POST is empty
    • Use isset($_POST['submit'])
    • Check $_SERVER['REQUEST_METHOD'] === 'POST'
    • Look with empty($_POST)
    Show answer

    Check $_SERVER['REQUEST_METHOD'] === 'POST' — Correct. The REQUEST_METHOD check does not depend on the submit button name; it is the most robust way.

  3. Match the form handling concepts

    method="post"
    Data in the body
    $_POST['name']
    Value of name field
    REQUEST_METHOD
    Request method
    ?? ''
    Missing key default

All lessons in Beginner