PHP Superglobals

What Are Superglobals?

Superglobals are built-in PHP variables that are always accessible, regardless of scope. You can access them anywhere in your code.

Common Superglobals

  • $_GET – Data from URL query strings
  • $_POST – Data from HTML forms using POST
  • $_REQUEST – Combines GET, POST, and COOKIE
  • $_SERVER – Server and execution environment info
  • $_SESSION – Session data
  • $_COOKIE – Cookies
  • $_FILES – Uploaded files
  • $_ENV – Environment variables
  • $GLOBALS – Access all global variables

Example: $_GET

// URL: example.php?name=John
$name = $_GET['name'];
echo "Hello, $name!";

Example: $_POST

<form method="post">
  <input name="email">
  <button type="submit">Send</button>
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  echo $_POST["email"];
}

Example: $_SERVER

echo $_SERVER['SERVER_NAME'];
echo $_SERVER['REQUEST_METHOD'];

Example: $_SESSION

session_start();
$_SESSION["user"] = "Alice";
echo $_SESSION["user"];

Session must be started using session_start() before use.

Using $GLOBALS

$x = 5;
$y = 10;

function sum() {
  $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}

sum();
echo $z;  // 15

Security Tip

Always validate and sanitize input from $_GET, $_POST, and $_REQUEST to prevent security issues like XSS and SQL Injection.

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic