PHP Superglobals

Superglobals are built-in variables that are always available in every scope.

Superglobals are special built-in arrays that PHP makes available everywhere, without needing the global keyword.

SuperglobalHolds
$_GETData from the URL query string.
$_POSTData from a submitted form.
$_SERVERServer and request information.
$_SESSIONData stored across page visits.
$GLOBALSAll global variables.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Read the logged-in user's ID from $_SESSION to personalise a dashboard without querying the database.
  • Access $_COOKIE to retrieve a saved user-preference theme and apply it to every page render.
  • Use $_FILES to handle an uploaded profile photo and validate its MIME type before moving it.

More examples

Reading from $_SESSION

$_SESSION persists data across requests for the same user; session_start() must be called before any output.

Example · php
<?php
session_start();

$_SESSION['user_id'] = 42;
$_SESSION['role']    = 'admin';

// Later on any page:
if (isset($_SESSION['user_id'])) {
    echo "Logged in as user: {$_SESSION['user_id']}";
}

Reading a cookie

$_COOKIE exposes cookies sent by the browser; ?? provides a safe default when the cookie is absent.

Example · php
<?php
setcookie('theme', 'dark', time() + 86400 * 30, '/');

$theme = $_COOKIE['theme'] ?? 'light';
echo "<body class=\"theme-$theme\">";

Handling a file upload

$_FILES holds the uploaded file's metadata and temporary path; move_uploaded_file() safely moves it to permanent storage.

Example · php
<?php
if ($_FILES['avatar']['error'] === UPLOAD_ERR_OK) {
    $tmp  = $_FILES['avatar']['tmp_name'];
    $name = basename($_FILES['avatar']['name']);
    move_uploaded_file($tmp, "/uploads/$name");
    echo "Upload complete: $name";
}

Discussion

  • Be the first to comment on this lesson.