PHP Superglobals — $_GET, $_POST, $_SESSION, $_SERVER, and More
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 predefined associative arrays that are accessible from any scope without the global keyword, providing access to form data, server information, sessions, cookies, and environment variables.
Why It Matters
Every PHP web application reads from superglobals. When a user submits a form, the data arrives in $_POST. When you need the current URL, $_SERVER['REQUEST_URI'] has it. When you check if a user is logged in, $_SESSION contains their data. Superglobals are the bridge between the HTTP request and your PHP code. Understanding them means you can build interactive applications that respond to user input.
Real-World Use
A contact form reads $_POST['name'] and $_POST['email']. A login system checks $_SERVER['REQUEST_METHOD'] and validates credentials from $_POST. A file upload handler processes $_FILES. An API endpoint reads JSON from php://input and writes responses. Session management uses $_SESSION to persist user state across requests. DodaTech's login portal uses $_SESSION to maintain authenticated sessions and $_SERVER for request logging.
What You Will Learn
- $_GET and $_POST for form data handling
- $_SERVER for server and request information
- $_SESSION and $_COOKIE for state management
- $_FILES for file upload handling
- $_ENV for environment configuration
- $_REQUEST and $GLOBALS
- Security best practices for superglobals
Learning Path
flowchart LR A[Arrays] --> B[Superglobals
You are here] B --> C[Forms] C --> D[Sessions] D --> E[Cookies] style B fill:#f90,color:#fff
What Are Superglobals?
Superglobals are built-in PHP arrays that are always available in every scope, including inside functions and classes. You do not need global to access them.
| Superglobal | Purpose |
|---|---|
$_GET |
URL query parameters |
$_POST |
HTTP POST form data |
$_REQUEST |
Combined GET and POST data |
$_SERVER |
Server and request metadata |
$_SESSION |
Session variables |
$_COOKIE |
HTTP cookies |
$_FILES |
Uploaded file data |
$_ENV |
Environment variables |
$GLOBALS |
All global variables |
$_GET -- Query Parameters
$_GET contains parameters from the URL query string:
// URL: http://example.com/search.php?q=php+tutorials&page=2
echo $_GET['q']; // php tutorials
echo $_GET['page']; // 2
echo $_SERVER['QUERY_STRING']; // q=php+tutorials&page=2
Important: Never trust $_GET data. It comes from the URL, which users can manipulate:
<?php
// Always validate and sanitize
$search = isset($_GET['q']) ? trim($_GET['q']) : '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) {
$page = 1;
}
echo "Searching for: " . htmlspecialchars($search) . "\n";
echo "Page: $page\n";
$_POST -- Form Submission Data
$_POST contains data from HTTP POST requests, typically from form submissions:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = $_POST['name'] ?? '';
$email = $_POST['email'] ?? '';
$message = $_POST['message'] ?? '';
// Validate
$errors = [];
if (empty($name)) $errors[] = 'Name is required';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Valid email is required';
}
if (empty($message)) $errors[] = 'Message is required';
if (empty($errors)) {
echo "Thank you, $name! Your message has been sent.";
} else {
foreach ($errors as $error) {
echo "<p class='error'>$error</p>";
}
}
}
$_SERVER -- Server and Request Information
$_SERVER contains server environment and request metadata. Its most useful keys:
<?php
$server = $_SERVER;
echo "Request method: " . $server['REQUEST_METHOD'] . "\n";
echo "Request URI: " . $server['REQUEST_URI'] . "\n";
echo "User agent: " . ($server['HTTP_USER_AGENT'] ?? 'Unknown') . "\n";
echo "Client IP: " . ($server['REMOTE_ADDR'] ?? 'Unknown') . "\n";
echo "Server software: " . ($server['SERVER_SOFTWARE'] ?? 'Unknown') . "\n";
echo "Host name: " . $server['SERVER_NAME'] . "\n";
echo "Server port: " . $server['SERVER_PORT'] . "\n";
echo "Script name: " . $server['SCRIPT_NAME'] . "\n";
Expected output (varies by setup):
Request method: GET
Request URI: /test.php
User agent: Mozilla/5.0 ...
Client IP: 127.0.0.1
Server software: Apache/2.4.58
Host name: localhost
Server port: 80
Script name: /test.php
Key $_SERVER Variables
| Key | Description | Example |
|---|---|---|
REQUEST_METHOD |
HTTP method | GET, POST, PUT |
REQUEST_URI |
Full URI path | /page?id=1 |
HTTP_HOST |
Requested host | example.com |
HTTP_USER_AGENT |
Browser user agent string | Mozilla/5.0... |
REMOTE_ADDR |
Client IP address | 192.168.1.1 |
SERVER_NAME |
Server hostname | localhost |
SCRIPT_NAME |
Current script path | /index.php |
HTTPS |
Whether request is secure | on or unset |
$_SESSION -- Session Variables
Sessions persist data across requests. They are stored on the server, with only a session ID in a cookie:
<?php
session_start(); // Must be called before any output
// Store data in session
$_SESSION['user_id'] = 42;
$_SESSION['username'] = 'alice';
$_SESSION['login_time'] = time();
// Check if logged in
if (isset($_SESSION['user_id'])) {
echo "Welcome back, " . $_SESSION['username'];
}
// Destroy session on logout
// session_destroy();
Session data is stored on the server, so the user cannot manipulate it directly. Only the session ID travels to the client.
$_COOKIE -- HTTP Cookies
Cookies are stored on the client and sent with every request:
<?php
// Set a cookie that expires in 30 days
setcookie('theme', 'dark', time() + 86400 * 30, '/');
// Read cookie
$theme = $_COOKIE['theme'] ?? 'light';
echo "Current theme: $theme";
// Delete cookie
setcookie('theme', '', time() - 3600, '/');
Note: setcookie() must be called before any HTML output. Cookies are sent with HTTP headers.
$_FILES -- File Uploads
When a form includes file inputs, upload data goes to $_FILES:
<?php
// HTML form must have: enctype="multipart/form-data"
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['document'])) {
$file = $_FILES['document'];
echo "Filename: " . $file['name'] . "\n";
echo "Type: " . $file['type'] . "\n";
echo "Size: " . $file['size'] . " bytes\n";
echo "Temp path: " . $file['tmp_name'] . "\n";
// Validate and move
$allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
if (in_array($file['type'], $allowedTypes) && $file['error'] === UPLOAD_ERR_OK) {
$dest = 'uploads/' . basename($file['name']);
move_uploaded_file($file['tmp_name'], $dest);
echo "File saved to: $dest";
} else {
echo "Invalid file type or upload error.";
}
}
$_ENV -- Environment Variables
Environment variables are useful for configuration that differs between development and production:
<?php
// Set in .env file or server config
// APP_ENV=production
// DB_HOST=localhost
$env = $_ENV['APP_ENV'] ?? 'development';
$dbHost = $_ENV['DB_HOST'] ?? 'localhost';
echo "Environment: $env\n";
echo "Database host: $dbHost\n";
For production applications, use a library like vlucas/phpdotenv to load .env files.
$_REQUEST -- Combined Request Data
$_REQUEST combines $_GET, $_POST, and $_COOKIE. It is convenient but insecure because you cannot tell where the data came from:
// URL: /page.php?id=5&action=delete
// Form POST: name=Alice
echo $_REQUEST['id']; // 5 (from GET)
echo $_REQUEST['name']; // Alice (from POST)
Prefer using $_GET and $_POST explicitly to avoid confusion.
Security Best Practices
Input Validation and Sanitization
Never use superglobal values directly in sensitive operations:
<?php
// BAD: directly using user input
$query = "SELECT * FROM users WHERE id = " . $_GET['id']; // SQL injection!
// GOOD: validate and use prepared statements
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if ($id === false) {
die('Invalid ID');
}
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([$id]);
XSS Prevention
Always escape output that came from superglobals:
<?php
// BAD: direct output
echo "Welcome, " . $_GET['name'];
// GOOD: escaped output
echo "Welcome, " . htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');
Common Mistakes
1. Not Checking If a Key Exists
echo $_POST['email']; // Warning if form field is empty
Use the null coalescing operator: $_POST['email'] ?? ''
2. Trusting $_FILES['file']['type']
The MIME type in $_FILES is sent by the client and can be faked. Validate file content instead:
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $file['tmp_name']);
3. Outputting $_SERVER Variables Without Escaping
echo $_SERVER['HTTP_USER_AGENT']; // XSS risk
Always use htmlspecialchars().
4. Not Calling session_start() Before Using $_SESSION
$_SESSION['user'] = 'Alice'; // Not available without session_start()
5. Using $_REQUEST When Specificity Is Needed
if ($_REQUEST['delete']) { /* Could be GET or POST */ }
Use $_POST['delete'] for POST-only actions like deletion.
Practice Questions
Why should you not trust $_GET and $_POST data directly? Users can manipulate URLs and POST data. Always validate, sanitize, and escape before using.
What superglobal contains the current page's URL?
$_SERVER['REQUEST_URI']contains the path and query string.How do sessions persist data across requests without exposing data to the client? The server stores session data locally. Only a session ID travels between server and client as a cookie.
What does filter_input do compared to accessing superglobals directly? filter_input reads and filters a superglobal value in one step. It returns false if validation fails.
Challenge: Build a simple request logger that records the IP address, user agent, request URI, and timestamp of every Visitor to a log file.
Mini Project: User Feedback Form
Create a PHP script that handles a feedback form with superglobals:
<?php
$errors = [];
$success = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = trim($_POST['name'] ?? '');
$rating = (int)($_POST['rating'] ?? 0);
$comments = trim($_POST['comments'] ?? '');
if (empty($name)) $errors[] = 'Name is required';
if ($rating < 1 || $rating > 5) $errors[] = 'Rating must be 1-5';
if (empty($comments)) $errors[] = 'Comments are required';
if (empty($errors)) {
file_put_contents('feedback.log',
date('Y-m-d H:i:s') . " | $name | $rating | $comments\n",
FILE_APPEND
);
$success = true;
}
}
?>
<!DOCTYPE html>
<html>
<body>
<?php if ($success): ?>
<p>Thank you for your feedback!</p>
<?php else: ?>
<?php foreach ($errors as $error): ?>
<p class="error"><?= htmlspecialchars($error) ?></p>
<?php endforeach; ?>
<form method="post">
<input type="text" name="name" placeholder="Your name">
<select name="rating">
<option value="">Rating</option>
<?php for ($i = 1; $i <= 5; $i++): ?>
<option value="<?= $i ?>"><?= $i ?></option>
<?php endfor; ?>
</select>
<textarea name="comments" placeholder="Comments"></textarea>
<button type="submit">Submit</button>
</form>
<?php endif; ?>
</body>
</html>
FAQ
What is Next
Now that you understand superglobals, proceed to Forms to build interactive web forms with validation. Then read Sessions to implement user login and session management.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro