Superglobals

Superglobals are built-in arrays available everywhere in PHP. Use them carefully with validation, sanitization, and escaping.

SuperglobalPurpose
$_GETQuery string parameters (URL)
$_POSTForm data sent via POST
$_REQUESTMix of GET/POST/COOKIE (not recommended)
$_SERVERServer and request metadata
$_SESSIONPer-user session storage
$_COOKIEClient-side small key-value storage
$_FILESUploaded 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

GoalUseExample
Validate intFILTER_VALIDATE_INTfilter_input(INPUT_GET,'id', FILTER_VALIDATE_INT)
Validate emailFILTER_VALIDATE_EMAILfilter_var($email, FILTER_VALIDATE_EMAIL)
Sanitize textFILTER_SANITIZE_SPECIAL_CHARSThen output with htmlspecialchars
Escape HTML outputhtmlspecialchars(..., ENT_QUOTES, 'UTF-8')Prevent XSS
DB queriesPrepared statements$stmt = $pdo->prepare('SELECT ... WHERE id=?')

9) Common Pitfalls

PitfallWhyFix
Trusting $_REQUESTMixes sources; unexpected overridingUse $_GET/$_POST explicitly
Printing raw user inputXSS riskhtmlspecialchars when outputting
Checking IP from X-Forwarded-ForHeader can be forgedTrust only via known proxy
Accepting file extension at face valueCan be fakedValidate with finfo MIME + size limits
No CSRF tokens on POSTCross-site requests possibleAdd per-session token and verify
No session ID regenerationSession fixationsession_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).