PHP Superglobals

Built-in variables accessible from anywhere in your script

🌍 What are PHP Superglobals?

Superglobals are built-in variables always accessible from any scope. They provide access to server information, user input, session data, and more without needing the global keyword.


<?php
// Access server information
echo $_SERVER['SERVER_NAME'];

// Get form data
$name = $_POST['username'];

// Access session data
$_SESSION['user_id'] = 123;
?>
                                    

Common Superglobals

📝

$_GET

Collects data from URL parameters. Used for passing information through links and retrieving search queries or page identifiers from the URL.

<?php
// URL: page.php?name=John
echo $_GET['name']; // John
?>
📮

$_POST

Collects data from HTML forms submitted with POST method. Secure way to send sensitive information like passwords and large amounts of data.

<?php
// From form submission
$email = $_POST['email'];
$password = $_POST['password'];
?>
🖥️

$_SERVER

Contains server and execution environment information. Access details like server name, request method, user agent, IP address, and script location.

<?php
echo $_SERVER['HTTP_HOST'];
echo $_SERVER['REQUEST_METHOD'];
?>
🔐

$_SESSION

Stores user-specific data across multiple pages. Perfect for maintaining login status, shopping carts, and user preferences throughout a browsing session.

<?php
session_start();
$_SESSION['username'] = "John";
?>
🍪

$_COOKIE

Accesses cookies stored on the user's browser. Store small pieces of data that persist across sessions, like user preferences or tracking information.

<?php
setcookie("user", "John", time()+3600);
echo $_COOKIE['user'];
?>
📁

$_FILES

Handles file uploads from HTML forms. Access uploaded file information including name, size, type, and temporary location for processing uploads.

<?php
$filename = $_FILES['upload']['name'];
$filesize = $_FILES['upload']['size'];
?>

🔹 $_GET Superglobal

Collect data sent via URL parameters:

<?php
// URL: welcome.php?name=Alice&age=25

if(isset($_GET['name'])) {
    $name = $_GET['name'];
    echo "Welcome, $name!<br>";
}

if(isset($_GET['age'])) {
    $age = $_GET['age'];
    echo "You are $age years old.";
}
?>

<!-- Create a link with parameters -->
<a href="welcome.php?name=Bob&age=30">Visit Bob's Page</a>

Output (when URL is welcome.php?name=Alice&age=25):

Welcome, Alice!

You are 25 years old.

🔹 $_POST Superglobal

Collect data from HTML form submissions:

<!-- HTML Form -->
<form method="POST" action="">
    <input type="text" name="username" placeholder="Username">
    <input type="email" name="email" placeholder="Email">
    <button type="submit" name="submit">Submit</button>
</form>

<?php
// Process form data
if(isset($_POST['submit'])) {
    $username = $_POST['username'];
    $email = $_POST['email'];
    
    echo "Username: $username<br>";
    echo "Email: $email";
}
?>

Output (after form submission):

Username: john_doe

Email: [email protected]

🔹 $_SERVER Superglobal

Access server and request information:

<?php
// Server information
echo "Server Name: " . $_SERVER['SERVER_NAME'];
echo "<br>";

// Request method (GET or POST)
echo "Request Method: " . $_SERVER['REQUEST_METHOD'];
echo "<br>";

// Current script name
echo "Script Name: " . $_SERVER['SCRIPT_NAME'];
echo "<br>";

// User's IP address
echo "User IP: " . $_SERVER['REMOTE_ADDR'];
echo "<br>";

// User's browser
echo "Browser: " . $_SERVER['HTTP_USER_AGENT'];
?>

Output:

Server Name: localhost

Request Method: GET

Script Name: /tutorial/server.php

User IP: 127.0.0.1

Browser: Mozilla/5.0 (Windows NT 10.0; Win64; x64)...

🔹 $_SESSION Superglobal

Store user data across multiple pages:

<?php
// Start session (required before using $_SESSION)
session_start();

// Set session variables
$_SESSION['username'] = "Alice";
$_SESSION['user_id'] = 101;
$_SESSION['role'] = "admin";

echo "Session started for: " . $_SESSION['username'];
echo "<br>";
echo "User ID: " . $_SESSION['user_id'];
echo "<br>";
echo "Role: " . $_SESSION['role'];

// Check if session variable exists
if(isset($_SESSION['username'])) {
    echo "<br>User is logged in!";
}
?>

Output:

Session started for: Alice

User ID: 101

Role: admin

User is logged in!

🔹 $_COOKIE Superglobal

Create and access cookies:

<?php
// Set a cookie (expires in 1 hour)
setcookie("user_preference", "dark_mode", time() + 3600);

// Set cookie with path
setcookie("language", "en", time() + 86400, "/");

// Access cookie (on next page load)
if(isset($_COOKIE['user_preference'])) {
    echo "Preference: " . $_COOKIE['user_preference'];
} else {
    echo "No preference set";
}

// Delete a cookie (set expiration to past)
setcookie("user_preference", "", time() - 3600);
?>

Output:

Preference: dark_mode

🔹 $_FILES Superglobal

Handle file uploads:

<!-- HTML Form -->
<form method="POST" enctype="multipart/form-data">
    <input type="file" name="upload">
    <button type="submit" name="submit">Upload</button>
</form>

<?php
if(isset($_POST['submit'])) {
    // File information
    $filename = $_FILES['upload']['name'];
    $filesize = $_FILES['upload']['size'];
    $filetype = $_FILES['upload']['type'];
    $temp_name = $_FILES['upload']['tmp_name'];
    
    echo "File Name: $filename<br>";
    echo "File Size: " . ($filesize / 1024) . " KB<br>";
    echo "File Type: $filetype<br>";
    
    // Move uploaded file
    move_uploaded_file($temp_name, "uploads/" . $filename);
    echo "File uploaded successfully!";
}
?>

Output:

File Name: document.pdf

File Size: 245.5 KB

File Type: application/pdf

File uploaded successfully!

🔹 $_REQUEST Superglobal

Access data from $_GET, $_POST, and $_COOKIE combined:

<?php
// $_REQUEST contains data from GET, POST, and COOKIE
// Can access any of them using $_REQUEST

// From URL: page.php?id=5
echo "ID from GET: " . $_REQUEST['id'];
echo "<br>";

// From POST form
if(isset($_REQUEST['username'])) {
    echo "Username: " . $_REQUEST['username'];
}

// Note: Use specific superglobals ($_GET, $_POST) for better security
?>

Output:

ID from GET: 5

Username: john_doe

🔹 Practical Example: Login System

Combine superglobals for a simple login:

<?php
session_start();

// Check if user is already logged in
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) {
    echo "Welcome back, " . $_SESSION['username'] . "!<br>";
    echo "<a href='?logout=true'>Logout</a>";
} else {
    // Handle logout
    if(isset($_GET['logout'])) {
        session_destroy();
        echo "Logged out successfully!<br>";
    }
    
    // Handle login
    if(isset($_POST['login'])) {
        $username = $_POST['username'];
        $password = $_POST['password'];
        
        // Simple validation (use proper authentication in production)
        if($username === "admin" && $password === "pass123") {
            $_SESSION['logged_in'] = true;
            $_SESSION['username'] = $username;
            echo "Login successful! Welcome, $username!";
        } else {
            echo "Invalid credentials!";
        }
    }
    
    // Show login form
    echo '<form method="POST">
        <input type="text" name="username" placeholder="Username"><br>
        <input type="password" name="password" placeholder="Password"><br>
        <button type="submit" name="login">Login</button>
    </form>';
}
?>

💡 Security Tips:

  • Validate Input: Always validate and sanitize user input from superglobals
  • Use isset(): Check if variables exist before using them
  • Escape Output: Use htmlspecialchars() to prevent XSS attacks
  • POST for Sensitive Data: Use $_POST instead of $_GET for passwords
  • Session Security: Regenerate session IDs after login

🧠 Test Your Knowledge

Which superglobal is used to collect form data sent with POST method?