PHP LogoSuper Global Variables ($_GET, $_POST, $_SESSION, etc.)

Super Global Variables in PHP are special, built-in variables that are always available in all scopes throughout a script. This means you can access them from any function, class, or file without needing to explicitly declare them as `global` or pass them as arguments. They are automatically accessible, making it easy to interact with request data, server information, and session management.

Here are some of the most commonly used Super Global Variables:

1. `$_GET`:
* Purpose: An associative array of variables passed to the current script via the URL parameters (query string).
* Method: Data is sent using the HTTP `GET` method.
* Visibility: The data is visible in the URL (e.g., `example.com/page.php?name=John&age=30`).
* Use Case: Retrieving data from query strings, simple data transfers, linking to specific content.

2. `$_POST`:
* Purpose: An associative array of variables passed to the current script via the HTTP `POST` method when submitting a form.
* Method: Data is sent using the HTTP `POST` method.
* Visibility: The data is not visible in the URL and is sent in the body of the HTTP request.
* Use Case: Sending sensitive data (like passwords), large amounts of data, file uploads (though `$_FILES` handles the actual file).

3. `$_REQUEST`:
* Purpose: An associative array that by default contains the contents of `$_GET`, `$_POST`, and `$_COOKIE`.
* Order: The order in which variables are populated in `$_REQUEST` is defined by the `variables_order` directive in `php.ini` (default is `GPCS` - Get, Post, Cookie, Server). If a variable exists in more than one source, the last one listed in `variables_order` will overwrite the previous ones.
* Use Case: Accessing data regardless of whether it came from GET or POST, though often `$_GET` or `$_POST` is preferred for clarity and security.

4. `$_SESSION`:
* Purpose: An associative array used to store information about a user across multiple page requests (i.e., maintaining a "session").
* Mechanism: PHP session management assigns a unique session ID to each user, usually stored in a cookie. This ID is then used to retrieve session data from the server.
* Requirement: Must be initialized with `session_start()` at the beginning of any script that uses sessions.
* Use Case: User authentication, shopping cart contents, personalized user preferences.

5. `$_COOKIE`:
* Purpose: An associative array of variables passed to the current script via HTTP cookies.
* Mechanism: Small pieces of data sent from the server to the user's web browser and stored by the browser. The browser then sends these cookies back to the server with subsequent requests.
* Setting: Cookies are set using the `setcookie()` function.
* Use Case: "Remember me" functionality, tracking user behavior, storing user preferences.

6. `$_SERVER`:
* Purpose: An associative array containing information created by the web server, about the execution environment, and the current request.
* Contents: Includes headers, paths, and script locations.
* Use Case: Getting the current script's filename (`$_SERVER['PHP_SELF']`), the request method (`$_SERVER['REQUEST_METHOD']`), the client's IP address (`$_SERVER['REMOTE_ADDR']`), and many more.

7. `$_FILES`:
* Purpose: An associative array of items uploaded to the current script via the HTTP POST method.
* Contents: Contains information about uploaded files such as their name, type, size, and temporary location.
* Use Case: Handling file uploads (images, documents, etc.).

8. `$_ENV`:
* Purpose: An associative array of variables passed to the script via the environment.
* Contents: Environment variables set by the operating system or web server configuration.
* Use Case: Accessing system-level environment variables, though `getenv()` is often preferred.

9. `$GLOBALS`:
* Purpose: An associative array containing references to all variables which are currently defined in the global scope of the script.
* Mechanism: The variable name is the key of the array. This means `$GLOBALS['var']` is equivalent to `$var`.
* Use Case: Less common than direct `global` keyword usage, but useful for iterating over global variables or dynamic access.

Understanding and properly using Super Global Variables is fundamental for building dynamic and interactive web applications with PHP. Always remember to sanitize and validate user input obtained through `$_GET`, `$_POST`, `$_REQUEST`, etc., to prevent security vulnerabilities like XSS and SQL injection.

Example Code

<?php
// Start the session for $_SESSION functionality. Must be called before any output.
session_start();

// Set a cookie (for demonstration of $_COOKIE). Must be called before any HTML output.
// We'll set it only if it doesn't exist to avoid 'headers already sent' warnings on refresh.
if (!isset($_COOKIE['my_cookie'])) {
    // setcookie(name, value, expire, path, domain, secure, httponly);
    setcookie('my_cookie', 'Hello from PHP Cookie!', time() + (86400 * 30), "/"); // Lasts 30 days
    $cookie_message = "<p>A cookie named 'my_cookie' has been set. Refresh the page to see its value.</p>";
} else {
    $cookie_message = "<p>Cookie 'my_cookie' value: " . htmlspecialchars($_COOKIE['my_cookie']) . "</p>";
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP Super Global Variables Example</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; line-height: 1.6; color: #333; background-color: #f4f4f4; }
        .container { max-width: 900px; margin: 0 auto; background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .section { margin-bottom: 30px; padding: 15px; border: 1px solid #ddd; border-left: 5px solid #007bff; background-color: #eef; border-radius: 5px; }
        h1 { color: #0056b3; text-align: center; margin-bottom: 30px; }
        h2 { color: #007bff; border-bottom: 1px solid #eee; padding-bottom: 10px; margin-top: 0; }
        pre { background-color: #f8f9fa; padding: 10px; border: 1px solid #ced4da; overflow-x: auto; font-family: 'Courier New', monospace; border-radius: 4px; }
        form label { display: block; margin-bottom: 5px; font-weight: bold; }
        form input[type="text"], form input[type="email"], form input[type="submit"] { padding: 10px; margin-bottom: 10px; border: 1px solid #ced4da; border-radius: 4px; width: calc(100% - 22px); box-sizing: border-box; }
        form input[type="submit"] { background-color: #28a745; color: white; cursor: pointer; border: none; width: auto; padding: 10px 20px; }
        form input[type="submit"]:hover { background-color: #218838; }
        a { color: #007bff; text-decoration: none; }
        a:hover { text-decoration: underline; }
        ul { list-style-type: none; padding: 0; }
        ul li { margin-bottom: 5px; background-color: #f0f8ff; padding: 8px; border-left: 3px solid #6c757d; }
    </style>
</head>
<body>
    <div class="container">
        <h1>PHP Super Global Variables Demonstration</h1>

        <!-- $_GET Example -->
        <div class="section">
            <h2>1. `$_GET` Variable</h2>
            <p>Data sent via the URL query string. Click the link below:</p>
            <p><a href="?name=Alice&city=NewYork">Visit with GET parameters</a></p>

            <?php
            if (isset($_GET['name'])) {
                echo "<p><strong>Hello, " . htmlspecialchars($_GET['name']) . " from " . htmlspecialchars($_GET['city']) . "!</strong></p>";
                echo "<p>Raw \$_GET content:</p>";
                echo "<pre>" . htmlspecialchars(print_r($_GET, true)) . "</pre>";
            } else {
                echo "<p>No 'name' parameter found in the URL. Try clicking the link above.</p>";
            }
            ?>
        </div>

        <!-- $_POST Example -->
        <div class="section">
            <h2>2. `$_POST` Variable</h2>
            <p>Data sent via an HTML form with `method="post"`.</p>
            <form action="" method="post">
                <label for="username">Username:</label>
                <input type="text" id="username" name="username" placeholder="Enter username" required>
                <br>
                <label for="email">Email:</label>
                <input type="email" id="email" name="email" placeholder="Enter email" required>
                <br>
                <input type="submit" name="submit_post" value="Submit via POST">
            </form>

            <?php
            if (isset($_POST['submit_post'])) {
                echo "<p><strong>Data received via POST:</strong></p>";
                echo "<p>Username: " . htmlspecialchars($_POST['username']) . "</p>";
                echo "<p>Email: " . htmlspecialchars($_POST['email']) . "</p>";
                echo "<p>Raw \$_POST content:</p>";
                echo "<pre>" . htmlspecialchars(print_r($_POST, true)) . "</pre>";
            }
            ?>
        </div>

        <!-- $_REQUEST Example -->
        <div class="section">
            <h2>3. `$_REQUEST` Variable</h2>
            <p>Combines `$_GET`, `$_POST`, and `$_COOKIE`.</p>
            <?php
            // Display $_REQUEST if any GET or POST data is present
            if (!empty($_REQUEST) && (isset($_GET['name']) || isset($_POST['username']) || isset($_COOKIE['my_cookie']))) {
                echo "<p>Raw \$_REQUEST content (shows GET/POST/COOKIE data):</p>";
                echo "<pre>" . htmlspecialchars(print_r($_REQUEST, true)) . "</pre>";
            } else {
                echo "<p>Submit a GET or POST form, or refresh after setting a cookie, to see \$_REQUEST data.</p>";
            }
            ?>
        </div>

        <!-- $_SESSION Example -->
        <div class="section">
            <h2>4. `$_SESSION` Variable</h2>
            <p>Stores data across multiple page requests for a user. (Session started at top of script)</p>
            <?php
            // Set and increment a session variable
            if (!isset($_SESSION['user_visits'])) {
                $_SESSION['user_visits'] = 1;
                echo "<p>Welcome! This is your first visit to this page in this session.</p>";
            } else {
                $_SESSION['user_visits']++;
                echo "<p>You have visited this page <strong>" . htmlspecialchars($_SESSION['user_visits']) . "</strong> times in this session.</p>";
            }

            // Set another session variable
            $_SESSION['favorite_color'] = 'blue';

            echo "<p>Your favorite color (from session) is: <strong>" . htmlspecialchars($_SESSION['favorite_color']) . "</strong></p>";
            echo "<p>Raw \$_SESSION content:</p>";
            echo "<pre>" . htmlspecialchars(print_r($_SESSION, true)) . "</pre>";

            // Example to destroy session (uncomment to enable logout link):
            /*
            echo "<p><a href=\"?action=logout\">Logout (Destroy Session)</a></p>";
            if (isset($_GET['action']) && $_GET['action'] == 'logout') {
                session_unset(); // Unset all session variables
                session_destroy(); // Destroy the session
                echo "<p><em>Session destroyed. Refresh the page to start a new session.</em></p>";
            }
            */
            ?>
            <p><em>Refresh the page to see `user_visits` increment.</em></p>
        </div>

        <!-- $_SERVER Example -->
        <div class="section">
            <h2>5. `$_SERVER` Variable</h2>
            <p>Contains information about the server and execution environment.</p>
            <p>Some common `$_SERVER` values:</p>
            <ul>
                <li><strong>`$_SERVER['PHP_SELF']`</strong>: <?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?></li>
                <li><strong>`$_SERVER['REQUEST_METHOD']`</strong>: <?php echo htmlspecialchars($_SERVER['REQUEST_METHOD']); ?></li>
                <li><strong>`$_SERVER['SERVER_NAME']`</strong>: <?php echo htmlspecialchars($_SERVER['SERVER_NAME']); ?></li>
                <li><strong>`$_SERVER['REMOTE_ADDR']`</strong>: <?php echo htmlspecialchars($_SERVER['REMOTE_ADDR']); ?></li>
                <li><strong>`$_SERVER['HTTP_USER_AGENT']`</strong>: <?php echo htmlspecialchars($_SERVER['HTTP_USER_AGENT']); ?></li>
            </ul>
            <p>Raw \$_SERVER content (partial, as it can be very large):</p>
            <pre><?php
                // Display a selection or a limited part of $_SERVER for brevity
                $server_info_to_display = array_filter($_SERVER, function($key) {
                    return in_array($key, ['PHP_SELF', 'REQUEST_METHOD', 'SERVER_NAME', 'REMOTE_ADDR', 'HTTP_USER_AGENT', 'SCRIPT_FILENAME', 'DOCUMENT_ROOT', 'SERVER_PROTOCOL']);
                }, ARRAY_FILTER_USE_KEY);
                echo htmlspecialchars(print_r($server_info_to_display, true));
            ?></pre>
        </div>

        <!-- $_COOKIE Example -->
        <div class="section">
            <h2>6. `$_COOKIE` Variable</h2>
            <p>Stores data on the client's browser. (Cookie set at top of script)</p>
            <?php
            echo $cookie_message; // Display message about cookie status
            echo "<p>Raw \$_COOKIE content:</p>";
            echo "<pre>" . htmlspecialchars(print_r($_COOKIE, true)) . "</pre>";
            ?>
        </div>

        <p style="text-align: center; margin-top: 40px; font-style: italic;">End of Super Global Variables Demonstration</p>
    </div>
</body>
</html>