Superglobals
Superglobals are built-in arrays available everywhere in PHP. Use them carefully with validation, sanitization, and escaping.
| Superglobal | Purpose |
|---|---|
$_GET | Query string parameters (URL) |
$_POST | Form data sent via POST |
$_REQUEST | Mix of GET/POST/COOKIE (not recommended) |
$_SERVER | Server and request metadata |
$_SESSION | Per-user session storage |
$_COOKIE | Client-side small key-value storage |
$_FILES | Uploaded files information |
1) $_GET (URL Parameters)
Use filter_input / filter_input_array to validate user input.
<?php
// URL: /page.php?id=42&q=hello
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
$q = filter_input(INPUT_GET, 'q', FILTER_SANITIZE_SPECIAL_CHARS);
if ($id === false) { die('Invalid id'); }
echo htmlspecialchars($q);
?>
Filter multiple
<?php
$data = filter_input_array(INPUT_GET, [
'page' => FILTER_VALIDATE_INT,
'search' => FILTER_SANITIZE_SPECIAL_CHARS,
]);
?>
2) $_POST (Form Data)
Use POST for actions that change state (create/update/delete). Always validate server-side.
<?php
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_SPECIAL_CHARS);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($email === false) { die('Invalid email'); }
// proceed: save to DB with prepared statements
}
?>
Avoid
$_REQUEST for security-sensitive logic. It mixes GET/POST/COOKIE; prefer $_GET or $_POST explicitly.3) $_SERVER (Request/Server Info)
<?php
$method = $_SERVER['REQUEST_METHOD'] ?? '';
$https = ($_SERVER['HTTPS'] ?? '') === 'on';
$uri = $_SERVER['REQUEST_URI'] ?? '/';
// Client IP (behind proxies use configured header carefully)
$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
?>
Note: Headers like
X-Forwarded-For can be forged. Trust only if your reverse proxy sets and you’ve whitelisted it.4) $_SESSION (State per User)
Start sessions before output. Regenerate IDs on login to prevent fixation. Destroy on logout.
<?php
session_start();
// Set / read
$_SESSION['user_id'] = 123;
$uid = $_SESSION['user_id'] ?? null;
// After successful login
session_regenerate_id(true);
// Logout
$_SESSION = [];
if (ini_get('session.use_cookies')) {
$p = session_get_cookie_params();
setcookie(session_name(), '', ['expires'=>time()-42000, 'path'=>$p['path']]);
}
session_destroy();
?>
5) $_COOKIE (Client-Side Storage)
Use secure attributes to protect cookies.
<?php
// Set cookie (PHP 7.3+ array options)
setcookie('theme', 'dark', [
'expires'=> time() + 86400*30,
'path'=> '/',
'secure'=> true, // only over HTTPS
'httponly'=> true, // JS cannot read
'samesite'=> 'Lax' // or 'Strict'
]);
// Read
$theme = $_COOKIE['theme'] ?? 'light';
?>
6) $_FILES (File Uploads)
Always validate size, type, and store outside webroot if possible. Use finfo to detect MIME, not extension.
<?php
// HTML form: <form method="post" enctype="multipart/form-data">
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST' && isset($_FILES['avatar'])) {
$f = $_FILES['avatar'];
if ($f['error'] !== UPLOAD_ERR_OK) { die('Upload error'); }
// size limit (2MB)
if ($f['size'] > 2*1024*1024) { die('Too large'); }
// real MIME
$fi = new finfo(FILEINFO_MIME_TYPE);
$mime = $fi->file($f['tmp_name']);
if (!in_array($mime, ['image/jpeg','image/png'], true)) {
die('Invalid type');
}
// safe filename
$name = bin2hex(random_bytes(8)) . ($mime === 'image/png' ? '.png' : '.jpg');
move_uploaded_file($f['tmp_name'], __DIR__ . "/uploads/" . $name);
}
?>
7) CSRF Protection Pattern
Generate a token in the session; include it in forms; verify on POST.
<?php
session_start();
if (empty($_SESSION['csrf'])) {
$_SESSION['csrf'] = bin2hex(random_bytes(32));
}
// In HTML form: <input type="hidden" name="csrf" value="<?= htmlspecialchars($_SESSION['csrf']) ?>">
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
$token = filter_input(INPUT_POST, 'csrf', FILTER_SANITIZE_STRING);
if (!hash_equals($_SESSION['csrf'], $token ?? '')) {
die('CSRF failed');
}
}
?>
8) Sanitization & Escaping Cheatsheet
| Goal | Use | Example |
|---|---|---|
| Validate int | FILTER_VALIDATE_INT | filter_input(INPUT_GET,'id', FILTER_VALIDATE_INT) |
| Validate email | FILTER_VALIDATE_EMAIL | filter_var($email, FILTER_VALIDATE_EMAIL) |
| Sanitize text | FILTER_SANITIZE_SPECIAL_CHARS | Then output with htmlspecialchars |
| Escape HTML output | htmlspecialchars(..., ENT_QUOTES, 'UTF-8') | Prevent XSS |
| DB queries | Prepared statements | $stmt = $pdo->prepare('SELECT ... WHERE id=?') |
9) Common Pitfalls
| Pitfall | Why | Fix |
|---|---|---|
Trusting $_REQUEST | Mixes sources; unexpected overriding | Use $_GET/$_POST explicitly |
| Printing raw user input | XSS risk | htmlspecialchars when outputting |
Checking IP from X-Forwarded-For | Header can be forged | Trust only via known proxy |
| Accepting file extension at face value | Can be faked | Validate with finfo MIME + size limits |
| No CSRF tokens on POST | Cross-site requests possible | Add per-session token and verify |
| No session ID regeneration | Session fixation | session_regenerate_id(true) after login |
10) Mini Demo (GET vs POST)
<?php
// GET: /php-superglobals.php?name=Sonu
$name = filter_input(INPUT_GET, 'name', FILTER_SANITIZE_SPECIAL_CHARS) ?? '';
echo $name ? "Hello, " . $name : "No name";
?>
Next: Continue with Forms & User Input for full examples (HTML forms, validation messages, sticky inputs, server-side + client-side checks).