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.
| Superglobal | Holds |
|---|---|
$_GET | Data from the URL query string. |
$_POST | Data from a submitted form. |
$_SERVER | Server and request information. |
$_SESSION | Data stored across page visits. |
$GLOBALS | All global variables. |
Example
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.
<?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.
<?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.
<?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