They’re accessible from any part of your code, regardless of functions, classes, or files, offering a convenient bridge for data exchange throughout your application. Let’s dive into these powerful variables, exploring their types, uses, and illustrative code examples.
Types of Superglobals:
PHP offers a diverse set of superglobals, each serving a distinct purpose:
$GLOBALS
: This superglobal holds all global variables within an array, allowing access to them from anywhere in your script.
$myGlobalVar = "Hello world!";
function myFunction() {
global $myGlobalVar;
echo $myGlobalVar; // Output: Hello world!
}
myFunction();
$_SERVER
: This superglobal stores information about the server and the current request, such as headers, user agent, IP address, and more.
echo $_SERVER['REMOTE_ADDR']; // Output: IP address of the client
echo $_SERVER['REQUEST_METHOD']; // Output: Request method (GET, POST, etc.)
$_GET
: Captures data passed through a URL’s query string (key-value pairs after the?
).
if (isset($_GET['name'])) {
echo "Hello, " . $_GET['name'] . "!";
}
$_POST
: Stores data submitted through an HTML form using the POST method.
if (isset($_POST['submit'])) {
echo "Username: " . $_POST['username'] . "<br>";
echo "Password: " . $_POST['password'];
}
$_FILES
: Accesses information about uploaded files, including name, size, and temporary location.
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
$_COOKIE
: Stores cookies, small pieces of data sent by a web server and stored on the user’s browser for later retrieval.
setcookie("username", "John", time() + 3600); // Set a cookie
echo "Welcome back, " . $_COOKIE['username'] . "!"; // Retrieve a cookie
$_SESSION
: Manages user sessions, allowing data to persist across multiple page requests.
session_start();
$_SESSION['user_id'] = 123;
echo "Your user ID is " . $_SESSION['user_id'];
Remember:
- Use superglobals judiciously, as excessive reliance can hinder code readability and maintainability.
- Prioritize security measures when handling user-provided data through superglobals, especially
$_GET
,$_POST
, and$_COOKIE
. - Consider alternative approaches like dependency injection for more structured data management in larger applications.