Superglobals in PHP
Superglobals in PHP
Superglobals in PHP are built-in global arrays that are always accessible, regardless of scope (i.e., inside functions or outside). They are used to gather and manipulate data from various sources such as form submissions, cookies, server variables, and more.
1. $_GET
The $_GET superglobal is used to collect form data after submitting an HTML form using the GET method. It is also used to collect query string parameters from the URL.
Example:
<?php// URL: example.com?name=John&age=25echo "Name: " . $_GET['name']; // Outputs: Johnecho "Age: " . $_GET['age']; // Outputs: 25?>$_GETis typically used for passing small amounts of data via the URL.The data passed through
$_GETcan be accessed via the key provided (e.g.,$_GET['name']).
2. $_POST
The $_POST superglobal is used to collect form data after submitting an HTML form using the POST method. It is used for sending data to the server that you do not want to expose in the URL.
Example:
<?php// In an HTML form// <form method="POST" action="process.php">// <input type="text" name="username" />// <input type="submit" value="Submit" />// </form>echo "Username: " . $_POST['username']; // Outputs the submitted username?>$_POSTis often used for forms that require sending sensitive data like passwords.The data is not visible in the URL, making it more secure than
$_GET.
3. $_REQUEST
The $_REQUEST superglobal contains the data from both $_GET and $_POST, as well as $_COOKIE. It can be used to collect form data, regardless of the HTTP method used.
Example:
<?php// Assuming the data comes from either GET or POST methodecho "Username: " . $_REQUEST['username']; // Works for both GET and POST?>$_REQUESTis a combination of$_GET,$_POST, and$_COOKIE. However, it is recommended to use$_GETor$_POSTexplicitly to avoid confusion and ensure better control over the input data.
4. $_SERVER
The $_SERVER superglobal contains information about the server environment, headers, paths, and script locations.
Example:
<?phpecho "Server Name: " . $_SERVER['SERVER_NAME']; // Outputs: example.comecho "Request Method: " . $_SERVER['REQUEST_METHOD']; // Outputs: GET or POSTecho "Current Script Name: " . $_SERVER['SCRIPT_NAME']; // Outputs the path of the current script?>Commonly used $_SERVER keys:
$_SERVER['REQUEST_METHOD']: The request method (GET, POST, etc.)$_SERVER['SERVER_NAME']: The name of the server (e.g.,example.com)$_SERVER['SERVER_ADDR']: The IP address of the server$_SERVER['HTTP_USER_AGENT']: Information about the user's browser$_SERVER['QUERY_STRING']: The query string from the URL
5. $_FILES
The $_FILES superglobal is used to handle file uploads. When a user submits a file through a form with the enctype="multipart/form-data" attribute, the file data is stored in $_FILES.
Example:
<?phpif ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['file'])) { // Get file name $fileName = $_FILES['file']['name']; // Get file temporary path $fileTmpName = $_FILES['file']['tmp_name']; // Get file size $fileSize = $_FILES['file']['size']; // Move uploaded file to the desired location move_uploaded_file($fileTmpName, "uploads/" . $fileName); echo "File uploaded successfully!";}?><form method="POST" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="Upload"></form>Key $_FILES attributes:
$_FILES['file']['name']: The original name of the file.$_FILES['file']['tmp_name']: The temporary name of the file on the server.$_FILES['file']['size']: The size of the uploaded file.$_FILES['file']['error']: Any error code associated with the file upload.
6. $_COOKIE
The $_COOKIE superglobal is used to access the values stored in cookies. Cookies are small pieces of data stored in the user's browser.
Example:
<?php// Setting a cookiesetcookie("user", "John", time() + 3600); // Cookie expires in 1 hour// Accessing the cookieecho "User: " . $_COOKIE['user']; // Outputs: John?>Cookies are set using the
setcookie()function.The data stored in
$_COOKIEis accessible on subsequent page loads until the cookie expires or is deleted.
7. $_SESSION
The $_SESSION superglobal is used to store and access session variables. Sessions allow you to store user-specific data across multiple page requests. Session data is stored on the server and is associated with a unique session ID, usually stored in a cookie.
Example:
<?php// Start the sessionsession_start();// Set session variables$_SESSION['username'] = "John";$_SESSION['role'] = "Admin";// Access session variablesecho "Username: " . $_SESSION['username']; // Outputs: John?>Sessions are started using
session_start().You can store and retrieve user-specific data that persists across page requests.
Session data is automatically stored on the server and associated with a unique session ID.
8. $_ENV
The $_ENV superglobal is used to access environment variables. Environment variables are often used to configure settings for the application or server.
Example:
<?php// Assuming the environment variable MY_ENV is setecho "Environment Variable: " . $_ENV['MY_ENV'];?>$_ENVis populated from the system's environment variables. It's commonly used in situations where the application needs to access server or environment-specific configuration settings.
9. $_GLOBALS
The $_GLOBALS superglobal is an associative array containing all global variables. It is used to access global variables from anywhere in the script.
Example:
<?php$a = 10; // Global variablefunction test() { // Access global variable $a using $_GLOBALS echo $_GLOBALS['a']; // Outputs: 10}test();?>$_GLOBALSis a way to access any global variable inside functions.
Summary of Common Superglobals
| Superglobal | Description |
|---|---|
$_GET | Collects data sent via URL parameters (GET method). |
$_POST | Collects data sent via form submissions (POST method). |
$_REQUEST | Collects data from both $_GET and $_POST (and $_COOKIE). |
$_SERVER | Provides server and execution environment information. |
$_FILES | Handles file uploads via forms. |
$_COOKIE | Stores and retrieves data in cookies. |
$_SESSION | Stores session variables for the duration of the user's session. |
$_ENV | Retrieves environment variables. |
$_GLOBALS | Accesses global variables from anywhere in the script. |
Conclusion
Superglobals in PHP are essential for handling data from various sources, such as forms, cookies, session variables, and server environment variables. They provide a flexible way to manage and manipulate data in a global scope, making them powerful tools for building dynamic web applications.