Understanding PHP Superglobals: A Comprehensive Guide
PHP Superglobals
PHP Superglobals are built-in variables in PHP that are always accessible, regardless of scope. They facilitate data handling across different contexts, such as forms, sessions, and server information. This guide provides an overview of the main superglobals and their applications.
Key Superglobals
- An associative array containing all global variables.
- Allows access to global variables from any scope.
- An array containing information about the server and the current script.
- Useful for retrieving headers, paths, and script locations.
- Combines
$_GET
,$_POST
, and$_COOKIE
data. - Used to collect data after submitting forms.
- An associative array of variables passed to the script via HTTP POST method.
- Commonly used to collect form data.
- An associative array of variables passed to the script via URL parameters.
- Useful for retrieving data when a form is submitted using the GET method.
- An associative array of items uploaded to the current script via HTTP POST.
- Used to handle file uploads.
- An associative array used to store session variables.
- Useful for maintaining user state across multiple pages.
- An associative array of variables passed to the script via HTTP cookies.
- Used to retrieve cookie values set in the user's browser.
$_COOKIE
php
echo $_COOKIE['user']; // Outputs the value of the cookie named 'user'
$_SESSION
php
session_start();
$_SESSION['username'] = 'Alice'; // Store session variable
$_FILES
php
// Assuming a file input named 'fileUpload'
echo $_FILES['fileUpload']['name']; // Outputs the name of the uploaded file
$_GET
php
// URL: example.com/index.php?name=John
echo $_GET['name']; // Outputs 'John'
$_POST
php
// Assuming a form with method="post" and a field named 'email'
echo $_POST['email'];
$_REQUEST
php
// Assuming a form with a field named 'username'
echo $_REQUEST['username'];
$_SERVER
php
echo $_SERVER['SERVER_NAME']; // Outputs the server name
$GLOBALS
php
$x = 10;
function test() {
$GLOBALS['x'] += 5; // Accesses global $x
}
test(); // $x is now 15
Conclusion
PHP Superglobals provide a convenient way to access data from various sources within your PHP applications. By understanding how to use these superglobals effectively, you can manage data efficiently across different parts of your web applications.