Receiving data with $_POST
Learn to receive form-submitted data with $_POST.
Receiving data with $_POST
The $_POST superglobal stores form data carried in the body of an HTTP POST request as an associative array. When a form is submitted with method='post', each field's name attribute becomes the key.
For example, a field with name='email' yields $_POST['email'] holding the typed text. POST data is not visible in the URL, which suits passwords and long forms. In CLI $_POST is empty; you can fill it by hand for testing.
Checking for missing keys with ??
A form does not always send every field you expect, so checking the $_POST key before use is essential. PHP's ?? operator (null coalescing) gives a default for missing keys.
Example: $name = $_POST['name'] ?? 'Guest';. If the form has no name field, $_POST['name'] is replaced by 'Guest'. This is shorter than isset() and works safely with missing keys.
Exercise Set $_POST values and print them
Set $_POST['username'] = "ayse"; and $_POST['email'] = "ayse@test.com";. Then use echo to produce this output: user: ayse, email: ayse@test.com followed by "\n".
Show example solution
$_POST['username'] = "ayse"; and $_POST['email'] = "ayse@test.com";. Then write echo "user: " . $_POST['username'] . ", email: " . $_POST['email'] . "\n";.
Example solution:
<?php
// Set $_POST values and print them
$_POST['username'] = "ayse";
$_POST['email'] = "ayse@test.com";
echo "user: " . $_POST['username'] . ", email: " . $_POST['email'] . "\n";
Test yourself
-
A field name='email' is sent with POST. How do you read it?
- $_POST[email]
- $_GET['email']
- $_SERVER['email']
- $_POST['email']
Show answer
$_POST['email'] — Correct. POST fields live in $_POST and the key is written in quotes.
-
Give a default for a missing key with ??
$name = $_POST[____] ?? "Guest";Show answer
$name = $_POST['name'] ?? "Guest"; -
Match the form field to its $_POST key
- name='email'
- $_POST['email']
- name='pass'
- $_POST['pass']
- name='age'
- $_POST['age']
- name='city'
- $_POST['city']