HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Superglobals

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).


1. List of Superglobals

PHP has nine predefined variables that are superglobals:

  • $GLOBALS
  • $_SERVER
  • $_REQUEST
  • $_POST
  • $_GET
  • $_FILES
  • $_ENV
  • $_COOKIE
  • $_SESSION

2. The $GLOBALS Variable

This 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
?>

3. The $_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;
?>
Always Available: Unlike regular variables, superglobals don't need to be declared within a function to be used. They are "super" because they transcend scope boundaries.
Context Matters: While $_REQUEST is convenient, it's safer to use the specific method ($_GET or $_POST) to ensure you are receiving data from the expected source.

Core Superglobals at a Glance

Variable Primary Use
$_SERVERServer and execution environment info.
$_GETData sent via URL parameters.
$_POSTData sent via form body.
$_SESSIONPersistent user data across pages.
$_COOKIEData stored on user's browser.
$_FILESUploaded file metadata and content.