What Are Superglobals in PHP: Simple Explanation and Examples
superglobals are built-in variables that are always accessible from any part of your script without needing to declare them. They provide easy access to important information like form data, server details, and session info.How It Works
Think of superglobals as special boxes that PHP always keeps open for you. No matter where you are in your code, you can reach into these boxes to get or set information without passing them around. This is different from normal variables that only work inside the place where you create them.
For example, when a user submits a form on a website, PHP automatically fills one of these boxes with the form data. You can then grab that data from anywhere in your script easily. This makes handling user input, server info, and session data straightforward and consistent.
Example
This example shows how to use the $_GET superglobal to get data sent in the URL query string.
<?php // URL example: script.php?name=Alice if (isset($_GET['name'])) { echo "Hello, " . htmlspecialchars($_GET['name']) . "!"; } else { echo "Hello, guest!"; } ?>
When to Use
Use superglobals whenever you need to access common data like user input, cookies, sessions, or server info without extra setup. For example, $_POST is perfect for handling form submissions securely, while $_SESSION helps keep track of user login status across pages.
They are essential in web development for tasks like processing forms, managing user sessions, and reading server environment details.
Key Points
- Superglobals are always available in all scopes without needing
global. - Common superglobals include
$_GET,$_POST,$_SESSION, and$_SERVER. - They simplify accessing important data like form inputs, cookies, and server info.
- Always sanitize data from superglobals to keep your app secure.