php · level 2 · unit 4 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A brings the visitor's answers to your code.
When someone visits a page, their browser sends a request. A GET request asks for a page, and any extras ride along in the address, like ?page=2. When they fill in a and press send, the browser makes a POST request carrying their answers.
PHP unpacks each request into superglobals, ready-made arrays filled in by the web server. $_GET holds the address extras, $_POST holds the form answers, and $_SERVER["REQUEST_METHOD"] says "GET" or "POST". Every value arrives as a string.
Gwecode has no real visitors, so you play the browser. Fill these arrays yourself at the top, then write the rest exactly as a real website would.
<?php
$_SERVER["REQUEST_METHOD"] = "POST";
$_POST = ["name" => "Priya", "tickets" => "2"];
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = $_POST["name"];
$tickets = (int) $_POST["tickets"];
echo "Thanks, $name! You booked $tickets tickets.\n";
} else {
echo "Please fill in the form.\n";
} Like $typed_name in Level 1, the pretend lines at the top stand in for a real visitor.
guess first
A visitor asks for page 3. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$_GET = ["page" => "3"];
$page = $_GET["page"];
echo gettype($page) . "\n";
echo $page === 3 ? "Page three\n" : "Not the number 3\n";
your turn
Your turn. Play the browser.
Type POST or GET in the first blank, and a dish in the second. Run it, then switch the first blank and run it again.
fix it
Kim pressed sign up, but nothing happened. Fix it.
- The request was a POST, so why did the
elserun? Compare line 2 with line 4. ===cares about capital letters, and request types are always written in capitals.- Change
"post"to"POST"on line 4, then press run.
nailed it
you can read what a visitor sends. :D
- A form sends a POST request, and an address sends a GET.
$_POSTand$_GEThold the answers, all as strings.- In Gwecode, you fill them in at the top yourself.
new words in your collection
- request
- form
- superglobal
This lesson isn’t saved. A free account remembers every lesson you finish.