HTTP Superglobals ($_GET, $_POST)
Superglobals are built-in variables that are globally accessible in all scopes. They handle HTTP client requests and server parameters.
1 Query Strings ($_GET) vs. Request Payloads ($_POST)
Common PHP superglobals include:
- $_GET: Collects parameters sent via the URL query string (e.g. `?id=5`). Visible in the browser address bar.
- $_POST: Collects parameters sent via HTTP POST requests (e.g. submitted HTML forms). Form data is hidden inside the request payload, making it secure for passwords.
- $_SERVER: Stores server configuration parameters and headers, such as user agents and request methods.
2 Superglobals Code
Let's look at an example illustrating superglobal properties:
PHP — Superglobals
▶ Run Code
<?php
// Simulating incoming HTTP context values inside arrays
$_GET['id'] = "105";
$_POST['username'] = "Balaji";
echo "GET parameter ID: " . $_GET['id'] . "\n";
echo "POST parameter Username: " . $_POST['username'] . "\n";
echo "Request Script Name: " . $_SERVER['SCRIPT_NAME'] . "\n";
?>
3 Code Challenge
Challenge: Write a script that checks if `$_SERVER['REQUEST_METHOD']` is equal to "POST". If it is, output the username parameter from `$_POST`; otherwise, print a warning message.