PHP Superglobals — Complete Guide to Built-in Global Variables
In this tutorial, you will learn about PHP Superglobals. We cover key concepts, practical examples, and best practices to help you master this topic.
PHP superglobals are built-in associative arrays that contain request data, server information, session data, and environment variables accessible from anywhere in a script.
What You'll Learn
By the end of this tutorial, you'll use all PHP superglobals: $_GET for URL parameters, $_POST for form data, $_SERVER for server info, $_SESSION for user state, and $_FILES for uploads.
Why Superglobals Matter
Superglobals bridge PHP with the web server, HTTP requests, and browser state. They provide access to everything needed to handle user input, maintain state, and understand the runtime environment.
Real-World Use
A login form uses $_POST for credentials, $_SESSION for the logged-in state, $_COOKIE for "remember me", $_SERVER for IP logging, and $_ENV for database configuration.
Superglobals Learning Path
flowchart LR
A[Include/Require] --> B[Superglobals]
B --> C[GET/POST]
C --> D[Cookies]
D --> E[Sessions]
A --> F{You Are Here}
style F fill:#f90,color:#fff
$_GET and $_POST
<?php
// URL: /page.php?name=Alice&age=25
echo $_GET["name"]; // Alice
echo $_GET["age"]; // 25
// Form with method="POST"
echo $_POST["email"];
echo $_POST["password"];
$_SERVER
<?php
echo $_SERVER["REQUEST_METHOD"]; // GET, POST, PUT, etc.
echo $_SERVER["REQUEST_URI"]; // /page.php?name=Alice
echo $_SERVER["HTTP_HOST"]; // example.com
echo $_SERVER["REMOTE_ADDR"]; // Client IP address
echo $_SERVER["HTTP_USER_AGENT"]; // Browser user agent
echo $_SERVER["SERVER_NAME"]; // Server hostname
$_SESSION
<?php
session_start();
$_SESSION["user_id"] = 42;
$_SESSION["role"] = "admin";
echo $_SESSION["user_id"]; // 42
$_COOKIE
<?php
setcookie("theme", "dark", time() + 86400);
echo $_COOKIE["theme"]; // dark
$_FILES
<?php
// Form: <input type="file" name="avatar">
$file = $_FILES["avatar"];
echo $file["name"]; // Original filename
echo $file["type"]; // image/jpeg
echo $file["size"]; // File size in bytes
echo $file["tmp_name"]; // Temporary path
$_REQUEST and $_ENV
<?php
// $_REQUEST combines GET, POST, and COOKIE
echo $_REQUEST["name"]; // Works for both GET and POST
// Environment variables
$_ENV["DB_HOST"] = "localhost";
echo getenv("DB_HOST"); // Also accessible via getenv()
Security with Superglobals
<?php
// Never trust superglobal values directly
$id = $_GET["id"];
$id = filter_var($id, FILTER_VALIDATE_INT);
if ($id === false) die("Invalid ID");
// Use null coalescing for defaults
$page = $_GET["page"] ?? 1;
$search = trim($_GET["q"] ?? "");
// Escape output
echo htmlspecialchars($_GET["name"], ENT_QUOTES, "UTF-8");
Common Mistakes
1. Using $_REQUEST Instead of $_GET or $_POST
$_REQUEST is ambiguous (GET, POST, COOKIE). Always use $_GET or $_POST explicitly.
2. Trusting $_SERVER Values
HTTP headers like HTTP_USER_AGENT and HTTP_REFERER are easily spoofed. Don't rely on them for security.
3. Accessing Undefined Keys
Accessing $_GET["undefined"] triggers a warning. Use isset() or null coalescing ($_GET["key"] ?? default).
4. Not Sanitizing $_FILES Data
Filenames can contain path traversal sequences like "../../etc/passwd". Always validate and sanitize.
5. Exposing $_SERVER in Error Messages
Displaying $_SERVER values in error messages reveals server paths and configuration.
Practice Questions
1. What are PHP superglobals?
Built-in global arrays accessible anywhere in a PHP script, containing request, server, session, and environment data.
2. What is the difference between $_GET and $_POST?
$_GET contains URL query parameters (visible in URL). $_POST contains form data sent in the request body (not visible).
3. Which superglobal contains the client's IP address?
$_SERVER["REMOTE_ADDR"]. Note that proxies may set HTTP_X_FORWARDED_FOR.
4. How do you safely access a $_GET parameter with a default?
$value = $_GET["key"] ?? "default"; This avoids warnings if the key is missing.
5. Challenge: Create a function that safely reads and sanitizes input from any superglobal.
<?php
function safeInput(string $key, string $method = "GET", mixed $default = null): mixed {
$source = $method === "POST" ? $_POST : $_GET;
$value = $source[$key] ?? $default;
if (is_string($value)) {
$value = trim($value);
}
return $value;
}
echo safeInput("name", "GET", "Guest");
FAQ
Mini Project: Request Inspector
Build a debug page that displays all request data safely.
<?php
function inspectRequest(): array {
return [
"method" => $_SERVER["REQUEST_METHOD"],
"uri" => $_SERVER["REQUEST_URI"],
"query" => array_map("htmlspecialchars", $_GET),
"body" => $_POST,
"headers" => [
"userAgent" => $_SERVER["HTTP_USER_AGENT"] ?? "unknown",
"host" => $_SERVER["HTTP_HOST"] ?? "unknown",
"ip" => $_SERVER["REMOTE_ADDR"] ?? "unknown"
]
];
}
$info = inspectRequest();
echo json_encode($info, JSON_PRETTY_PRINT);
What's Next
PHP GET POST PHP Cookies PHP Sessions
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro