W3docs

PHP Superglobals

PHP is a widely used programming language, especially for web development. It offers several variables that are available in all scopes, called "superglobals".

PHP Superglobals

Superglobals are built-in PHP variables that are always available, in every scope, without any declaration. Unlike ordinary variables, you do not need to write global $var; to use them inside a function — they are visible everywhere automatically. They are the bridge between the outside world (the browser, the web server, the operating system) and your PHP script: incoming form data, cookies, session state, and request metadata all arrive through superglobals.

This chapter covers what each superglobal contains, when to reach for it, and the security pitfalls that trip up most beginners.

What are PHP superglobals?

A superglobal is a predefined associative array that PHP fills in for you before your script runs. There are nine superglobals:

SuperglobalHoldsTypical use
$_GETQuery-string parameters (?key=value)Search, pagination, filters
$_POSTForm fields submitted in the request bodyLogin, sign-up, data entry
$_REQUESTMerge of $_GET, $_POST, and $_COOKIEConvenience (use with caution)
$_FILESFiles uploaded via a multipart formFile / image uploads
$_COOKIECookies sent by the browser"Remember me", preferences
$_SESSIONPer-user data stored on the serverLogin state, shopping carts
$_SERVERServer and request information (headers, paths)Routing, detecting the HTTP method
$_ENVEnvironment variablesConfiguration, secrets, API keys
$GLOBALSAll variables in the global scopeReaching globals from inside a function

Because they are arrays, you read a value by key — for example $_GET['name'] — and you can inspect the whole array with print_r() or var_dump() while debugging.

Security first. Everything in $_GET, $_POST, $_REQUEST, $_COOKIE, and $_FILES comes from the user and must be treated as untrusted. Always check that a key exists, then validate and escape it before use. Skip this and you open the door to XSS, SQL injection, and broken logic.

$_GET

$_GET collects parameters from the URL query string. For the URL example.com/?name=John&page=2, PHP populates $_GET like this:

// URL: example.com/?name=John&page=2
$_GET = ['name' => 'John', 'page' => '2'];

$name = $_GET['name'] ?? 'guest';   // 'John'
$page = (int) ($_GET['page'] ?? 1); // 2
echo "Hello, $name — viewing page $page";

Use $_GET for data that is safe to expose in the URL and that can be bookmarked or shared: search terms, page numbers, sort order. Note the ?? (null coalescing) operator — it provides a fallback so missing keys do not raise an "undefined array key" warning. Never put passwords or sensitive data in $_GET, because the URL is logged, cached, and visible in the address bar.

$_POST

$_POST collects data sent in the HTTP request body, typically from a form with method="post". The values are not shown in the URL, which makes $_POST the right choice for login forms and any action that changes data.

// <form method="post"><input name="email"> ... </form>
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "Stored: $email";
    } else {
        echo "Please enter a valid email address.";
    }
}

Both $_GET and $_POST are central to working with forms — see PHP Form Handling and PHP Form Validation for complete, validated examples.

$_REQUEST

$_REQUEST is a convenience array that merges $_GET, $_POST, and $_COOKIE. It lets you read a value regardless of how it was sent:

$id = $_REQUEST['id'] ?? null;

Use it sparingly. Because the order in which the three sources overwrite each other is controlled by the request_order setting in php.ini, a cookie could silently shadow a POST field. For predictable, secure code, prefer the specific superglobal ($_GET or $_POST) that you actually expect.

$_FILES

$_FILES holds metadata about files uploaded through a form that uses enctype="multipart/form-data". For an input named avatar, you get an array with the original name, MIME type, temporary path, error code, and size:

// <form method="post" enctype="multipart/form-data">
//   <input type="file" name="avatar">
// </form>
if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] === UPLOAD_ERR_OK) {
    $tmp  = $_FILES['avatar']['tmp_name'];
    $name = basename($_FILES['avatar']['name']);
    move_uploaded_file($tmp, __DIR__ . "/uploads/$name");
    echo "Uploaded $name";
}

Always check the error key and validate the file type and size before calling move_uploaded_file() — never trust the client-supplied name or type.

$_COOKIE contains the cookies the browser sent with the request. A cookie is a small piece of data stored in the browser and returned on every subsequent request, useful for remembering preferences or a "stay logged in" token.

// Cookies are set with setcookie(), then read on the NEXT request:
setcookie('theme', 'dark', time() + 86400); // expires in 1 day

$theme = $_COOKIE['theme'] ?? 'light';
echo "Current theme: $theme";

A cookie you set with setcookie() is not available in $_COOKIE until the next request, because it travels to the browser first and comes back afterwards. For the full lifecycle, see PHP Cookies.

$_SESSION

$_SESSION stores per-user data on the server, identified by a session ID that travels in a cookie. Because the data lives on the server, it is safer than a cookie for sensitive state such as "is this user logged in".

You must call session_start() before reading or writing $_SESSION:

session_start();

$_SESSION['user_id'] = 42;        // write
$id = $_SESSION['user_id'] ?? 0;  // read on any page
echo "Logged-in user: $id";

See PHP Sessions for a complete login example and details on session lifetime.

$_SERVER

$_SERVER is filled by the web server with information about the request and the environment. Common keys:

$method = $_SERVER['REQUEST_METHOD']; // 'GET' or 'POST'
$host   = $_SERVER['HTTP_HOST'];      // 'www.example.com'
$uri    = $_SERVER['REQUEST_URI'];    // '/products?id=5'
$ip     = $_SERVER['REMOTE_ADDR'];    // visitor's IP address

if ($method === 'POST') {
    echo "Handling a form submission from $ip";
}

$_SERVER['REQUEST_METHOD'] is the standard way to tell whether a page was loaded normally (GET) or a form was submitted (POST).

$_ENV and $GLOBALS

$_ENV exposes the operating-system environment variables, which is where modern apps keep configuration and secrets so they stay out of the source code:

$dbHost = $_ENV['DB_HOST'] ?? 'localhost';
$apiKey = getenv('API_KEY'); // getenv() also reads the environment

$GLOBALS is an array of every variable defined in the global scope. It lets a function reach a global variable without the global keyword:

$counter = 10;

function increment() {
    $GLOBALS['counter']++; // modifies the global $counter
}
increment();
echo $counter; // 11

$GLOBALS is rarely the right tool — passing data as function arguments is cleaner. To understand why, read PHP Variable Scope.

Conclusion

PHP superglobals are the standard way to read input and request information in a PHP web application. Use $_GET for URL parameters, $_POST for form submissions, $_FILES for uploads, $_COOKIE and $_SESSION for per-user state, and $_SERVER/$_ENV for request and environment details. The one rule that applies to all of them: data that originates from the browser is untrusted — validate and escape it every time. From here, continue with PHP Form Validation to see these superglobals applied to a real, secure form.

Practice

Practice
What are the different types of Superglobals in PHP?
What are the different types of Superglobals in PHP?
Was this page helpful?