PHP
What is a superglobal?
Learn that superglobal variables are accessible from any scope.
What is a superglobal?
A superglobal is an array variable predefined by PHP that you can reach from any scope directly. Inside a function you can use $_SERVER without the global keyword; it is automatically visible because it is super.
There are nine superglobals: $GLOBALS, $_SERVER, $_GET, $_POST, $_REQUEST, $_SESSION, $_COOKIE, $_ENV and $_FILES. Each one represents a different data source; for example $_GET carries URL parameters and $_POST carries the form body.
Access from any scope
A normal variable is not visible inside a function; you must bring it in with the global keyword. Superglobals are different: they can be used directly in a function body. This property is what makes them 'super'.
Example: function show() { echo $_SERVER['PHP_SELF']; }. Here $_SERVER is not a function parameter but a superglobal; no global is needed. That is why $_GET, $_POST and friends are easy to use inside request handlers.
Exercise Use $_SERVER inside a function
Define a parameterless function named showHost. In the body write echo $_SERVER['HTTP_HOST'];. Outside the function add $_SERVER['HTTP_HOST'] = "shop.test";. Then call showHost();.
Show example solution
Define with function showHost() { ... }, put echo $_SERVER['HTTP_HOST']; in the body, set $_SERVER['HTTP_HOST'] = "shop.test"; outside, then call showHost();.
Example solution:
<?php
// Define showHost and call it
$_SERVER['HTTP_HOST'] = "shop.test";
function showHost() {
echo $_SERVER['HTTP_HOST'];
}
showHost();
Test yourself
-
Which is NOT a superglobal?
- $_GET
- $_POST
- $_FORM
- $_SERVER
Show answer
$_FORM — Correct. There is no superglobal named $_FORM in PHP; form data lives in $_POST.
-
Complete the superglobal in the function
function showHost() {
echo ____['HTTP_HOST'];
}
Show answer
function showHost() {
echo $_SERVER['HTTP_HOST'];
}
-
Match each superglobal to its source
- $_GET
- URL parameters
- $_POST
- Form body
- $_SERVER
- Server info
- $_COOKIE
- Cookies
Next lesson: Receiving data with $_GET