PHP Superglobals
Superglobals are built-in PHP arrays that are automatically available inside every function, class, and file without any special declaration.
What are superglobals?
In most of PHP, whether a variable is visible depends on where it was created. A variable defined outside a function is not automatically usable inside that function. Superglobals break that rule on purpose: they are a small, fixed set of arrays that PHP fills in for you at the start of every request, and they can be read from any scope. This makes them the primary channel through which your script learns about the incoming HTTP request, the server, uploaded files, cookies, and session state.
Every superglobal name begins with a dollar sign and an underscore and is written in uppercase. Because they exist everywhere, you never pass them as function arguments and you never write the 'global' keyword to reach them.
Reading from a superglobal
Because superglobals are ordinary associative arrays, you read a value by its key. The key is the name of the field or the header you care about. Since the visitor controls many of these keys, always check that a key exists before you use it.
Inspecting the current request
<?php
// The request method tells you how the page was loaded.
$method = $_SERVER['REQUEST_METHOD'];
echo "This page was requested with: " . $method;
// Safely read a query string value with the null coalescing operator.
$page = $_GET['page'] ?? 'home';
echo "<p>Showing page: " . htmlspecialchars($page) . "</p>";
?>A closer look at $_SERVER
$_SERVER is the superglobal you will reach for most often outside of forms. It exposes useful facts about the running request, and unlike form data most of its entries are supplied by the web server rather than the visitor.
- $_SERVER['REQUEST_METHOD'] — the HTTP verb, such as GET or POST
- $_SERVER['PHP_SELF'] — the path of the currently executing script
- $_SERVER['HTTP_HOST'] — the host name from the request
- $_SERVER['REMOTE_ADDR'] — the IP address of the visitor
- $_SERVER['SERVER_NAME'] — the name of the host under which the script runs
Branching on the request method
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo "The form was submitted.";
} else {
echo "Waiting for the form to be sent.";
}
?>Exercise: PHP Superglobals
Why are $_GET and $_POST accessible directly inside any function?