Superglobals are built-in variables that are always available in all scopes. This means they can be accessed from any function, class, or file without having to do anything special (like using the global keyword).
PHP has nine predefined variables that are superglobals:
$GLOBALS$_SERVER$_REQUEST$_POST$_GET$_FILES$_ENV$_COOKIE$_SESSION$GLOBALS VariableThis is an associative array that contains references to all variables which are currently defined in the global scope of the script.
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z; // Output: 100
?>
$_REQUEST Variable$_REQUEST is used to collect data after submitting an HTML form. It contains the contents of both $_GET, $_POST, and $_COOKIE.
<?php
$name = $_REQUEST['fname'];
echo $name;
?>
$_REQUEST is convenient, it's safer to use the specific method ($_GET or $_POST) to ensure you are receiving data from the expected source.
| Variable | Primary Use |
|---|---|
$_SERVER | Server and execution environment info. |
$_GET | Data sent via URL parameters. |
$_POST | Data sent via form body. |
$_SESSION | Persistent user data across pages. |
$_COOKIE | Data stored on user's browser. |
$_FILES | Uploaded file metadata and content. |