Summary - Superglobals
Build a page that displays URL parameters using $_GET and $_SERVER.
Summary - Superglobals
In this group you met four core superglobals: $_GET for URL parameters, $_POST for the form body, $_SERVER for server and request info, and $_REQUEST which merges the three. All are reachable from any scope directly.
A request handling script typically checks $_SERVER['REQUEST_METHOD'] for the method, reads data with $_GET or $_POST, and gives defaults to missing keys with ??. In CLI, filling $_GET by hand with parse_str() makes testing easy.
Exercise Set up $_GET and $_SERVER and print them
Use parse_str() to fill $_GET with "name=Alex&role=admin". Set $_SERVER['REQUEST_METHOD'] = "GET";. Then write, in order, echo $_SERVER['REQUEST_METHOD'] . "\n";, echo $_GET['name'] . "\n"; and echo $_GET['role'] . "\n";.
Show example solution
$_SERVER['REQUEST_METHOD'], $_GET['name'], $_GET['role'], each ending with . "\n".
Example solution:
<?php
// Set up $_GET and $_SERVER and print them
parse_str("name=Alex&role=admin", $_GET);
$_SERVER['REQUEST_METHOD'] = "GET";
echo $_SERVER['REQUEST_METHOD'] . "\n";
echo $_GET['name'] . "\n";
echo $_GET['role'] . "\n";
Test yourself
-
Match the source to its superglobal
- URL parameters
- $_GET
- Form body
- $_POST
- Server info
- $_SERVER
- GET+POST+COOKIE
- $_REQUEST
-
Complete the parse_str call
parse_str("name=Alice", ____); echo $_GET['name'];Show answer
parse_str("name=Alice", $_GET); echo $_GET['name']; -
How do you access $_SERVER inside a function?
- You must write global $server;
- You must write use $_SERVER;
- You can write $_SERVER directly
- You must first return $_SERVER;
Show answer
You can write $_SERVER directly — Correct. $_SERVER is a superglobal, so inside a function you reach it without the global keyword.