PHP Superglobals
In this page:
What Are Superglobals?
Superglobals are built-in PHP arrays that are automatically available in every scope — inside any function or class method — without needing to be passed in or declared global. They exist to carry information about the current request, server environment, and session that any part of the application might need.
Example: What Are Superglobals?
<?php
function showUser() {
$_SESSION['user'] = "Alice"; // no `global` needed
echo $_SESSION['user'];
}
session_start();
showUser();
?>
Login to try C/C++/Java/PHP code in the editor
$_SERVER and $GLOBALS
$_SERVER holds request and server metadata such as the requested URL (REQUEST_URI), the HTTP method, and headers. $GLOBALS gives access to every variable declared in the global scope from inside a function, which is technically possible but generally avoided in favor of explicit parameters.
Example: $_SERVER and $GLOBALS
<?php
$_SERVER['REQUEST_URI'] = '/home';
echo $_SERVER['REQUEST_URI'] . "\n";
$name = "Alice";
function show() {
echo $GLOBALS['name'];
}
show();
?>
Login to try C/C++/Java/PHP code in the editor
$_SESSION and $_COOKIE
$_SESSION stores data that persists across multiple requests from the same visitor, backed by a session ID usually stored in a cookie, and requires session_start() before use. $_COOKIE reads the raw cookie values sent by the browser directly, without any server-side session logic involved.
Example: $_SESSION and $_COOKIE
<?php
session_start();
$_SESSION['user_id'] = 5;
$_COOKIE['theme'] = 'dark';
echo $_SESSION['user_id'] . " " . $_COOKIE['theme'];
?>
Login to try C/C++/Java/PHP code in the editor
$_FILES for Uploads
$_FILES is populated whenever a form submits with enctype="multipart/form-data", giving you each uploaded file's temporary path, original name, size, and any upload error code — all of which should be validated before the file is moved anywhere permanent.
Example: $_FILES for Uploads
<?php
$_FILES['avatar'] = ['name' => 'pic.png', 'tmp_name' => '/tmp/xyz', 'error' => 0];
if ($_FILES['avatar']['error'] === 0) {
echo "Upload OK: " . $_FILES['avatar']['name'];
}
?>
Login to try C/C++/Java/PHP code in the editor
$_ENV and Security Considerations
$_ENV exposes environment variables the web server was started with, often used for secrets like database credentials so they never appear in source code. Because every superglobal reflects untrusted external input except $_ENV and $GLOBALS, always validate before trusting their contents.
Example: $_ENV and Security Considerations
<?php
putenv("DB_PASSWORD=secret");
echo getenv("DB_PASSWORD") . "\n";
echo "Always validate superglobal input before trusting it";
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: