PHP Superglobals

Superglobals are built-in PHP variables that are always accessible from anywhere in a script — inside functions, classes, or nested includes — without needing the global keyword. PHP provides nine superglobal arrays, each serving a specific purpose: accessing form data, server information, uploaded files, cookies, sessions, and more.

$_GET — Query String Data

The $_GET superglobal holds data sent through the URL query string. When a URL like page.php?id=5&lang=en is accessed, PHP populates $_GET with those key-value pairs.

<?php
  // URL: page.php?id=5&lang=en

  $id = $_GET['id'];       // "5"
  $lang = $_GET['lang'];   // "en"

  echo "Page ID: " . $id;
  echo "Language: " . $lang;

  // Safe way to check if it exists first:
  $category = $_GET['category'] ?? 'all';
  echo "Category: " . $category;   // "all" if not in URL
?>

$_POST — Form Submission Data

The $_POST superglobal holds data submitted from an HTML form using the POST method. Unlike GET, this data does not appear in the URL.

<?php
  if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'] ?? '';
    $email = $_POST['email'] ?? '';

    echo "Received: " . htmlspecialchars($username);
  }
?>

$_REQUEST — Combined GET, POST, and COOKIE

$_REQUEST combines the data from $_GET, $_POST, and $_COOKIE into one array. However, using it is generally discouraged because it does not make the source of data explicit, which can introduce security issues.

<?php
  // Works for data sent via GET or POST
  $name = $_REQUEST['name'] ?? 'Guest';
  echo $name;
?>

$_SERVER — Server and Execution Information

$_SERVER contains information about the server environment, HTTP headers, and the request itself. It is extremely useful for detecting request types, getting the current page URL, and reading IP addresses.

<?php
  // Request method
  echo $_SERVER['REQUEST_METHOD'];       // GET or POST

  // Current script's filename
  echo $_SERVER['PHP_SELF'];             // /contact.php

  // Full URL hostname
  echo $_SERVER['HTTP_HOST'];            // www.example.com

  // Visitor's IP address
  echo $_SERVER['REMOTE_ADDR'];          // 192.168.1.1

  // Server software
  echo $_SERVER['SERVER_SOFTWARE'];      // Apache/2.4.54

  // The query string portion of the URL
  echo $_SERVER['QUERY_STRING'];         // id=5&lang=en
?>

$_FILES — Uploaded File Data

$_FILES contains information about files uploaded through an HTML form. The form must use method="post" and enctype="multipart/form-data".

<form method="post" action="" enctype="multipart/form-data">
  <input type="file" name="profilePhoto">
  <input type="submit" value="Upload">
</form>

<?php
  if (isset($_FILES['profilePhoto'])) {
    $file = $_FILES['profilePhoto'];

    echo "File name: " . $file['name'];       // original filename
    echo "File type: " . $file['type'];       // MIME type, e.g. image/jpeg
    echo "File size: " . $file['size'];       // Size in bytes
    echo "Temp path: " . $file['tmp_name'];   // Temporary location on server
    echo "Error code: " . $file['error'];     // 0 = no error

    if ($file['error'] === UPLOAD_ERR_OK) {
      move_uploaded_file($file['tmp_name'], "uploads/" . $file['name']);
      echo "Upload successful.";
    }
  }
?>

$_ENV — Environment Variables

$_ENV contains environment variables passed to PHP from the operating system. It is commonly used to read configuration values set in .env files or server configuration.

<?php
  $dbHost = $_ENV['DB_HOST'] ?? 'localhost';
  $appEnv = $_ENV['APP_ENV'] ?? 'production';

  echo "Database host: " . $dbHost;
  echo "Environment: " . $appEnv;
?>

$_SESSION — Session Variables

Sessions store user-specific data on the server across multiple page requests. $_SESSION holds session variables after calling session_start(). Sessions are covered in detail in their own topic.

<?php
  session_start();

  $_SESSION['user_id'] = 42;
  $_SESSION['username'] = "alice";

  echo "Logged in as: " . $_SESSION['username'];
?>

$_COOKIE — Cookie Data

Cookies store small pieces of data in the user's browser. $_COOKIE provides access to cookies that were previously set. Cookies are covered in their own topic.

<?php
  if (isset($_COOKIE['theme'])) {
    $theme = $_COOKIE['theme'];
    echo "User's preferred theme: " . $theme;
  } else {
    echo "No theme preference saved.";
  }
?>

$GLOBALS — Access Global Variables from Anywhere

$GLOBALS is an array of all global variables currently defined in the script. It provides an alternative way to access global variables inside functions without using the global keyword.

<?php
  $siteTitle = "My PHP Site";

  function displayTitle() {
    echo $GLOBALS['siteTitle'];   // Accesses global variable directly
  }

  displayTitle();   // Outputs: My PHP Site
?>

Summary of PHP Superglobals

SuperglobalPurpose
$_GETData from the URL query string
$_POSTData from POST form submissions
$_REQUESTCombined GET, POST, and COOKIE data
$_SERVERServer environment, headers, and request info
$_FILESUploaded file data
$_ENVOperating system environment variables
$_SESSIONServer-side session variables
$_COOKIEData stored in browser cookies
$GLOBALSAll globally defined variables

Key Points

  • Superglobals are always accessible anywhere in a script without the global keyword.
  • $_GET reads URL parameters; $_POST reads form body data.
  • $_SERVER provides request method, host, IP address, and other server information.
  • $_FILES handles file uploads; requires enctype="multipart/form-data" on the form.
  • Always use isset() or the null coalescing operator (??) before accessing superglobal values to avoid errors when keys do not exist.
  • Never trust superglobal data without validation and sanitization — it comes directly from users.

Leave a Comment

Your email address will not be published. Required fields are marked *