PHP - Superglobals
Superglobals in PHP are predefined variables that are accessible from any scope throughout a PHP script. They provide information about the server environment, request, and session management. Here are the main superglobals in PHP:
1. $_GET
$_GET
is an associative array of variables passed to the current script via the URL parameters
(query string) using the HTTP GET method.
Example:
Assuming the URL is http://example.com/?name=John&age=30
:
php<?php
echo $_GET['name']; // Outputs: John
echo $_GET['age']; // Outputs: 30
?>
2. $_POST
$_POST
is an associative array of variables passed to the current script via the HTTP POST method
when using forms with method="post"
.
Example:
php<form method="post" action="process.php">
<input type="text" name="username">
<input type="password" name="password">
<button type="submit">Submit</button>
</form>
<?php
echo $_POST['username']; // Accesses input from form submission
?>
3. $_REQUEST
$_REQUEST
is a merged array containing $_GET
, $_POST
, and
$_COOKIE
variables. It can handle data from both GET and POST requests.
Example:
php<?php
echo $_REQUEST['name']; // Works for both GET and POST requests
?>
4. $_FILES
$_FILES
is an associative array containing information about uploaded files via HTTP POST. It
contains file upload information such as file name, file type, and file size.
Example:
php<form method="post" action="upload.php" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
<?php
$file = $_FILES['file'];
echo $file['name']; // Outputs the uploaded file name
?>
5. $_COOKIE
$_COOKIE
is an associative array of variables passed to the current script via HTTP cookies.
Example:
php<?php
echo $_COOKIE['username']; // Outputs the value of the 'username' cookie
?>
6. $_SESSION
$_SESSION
is an associative array containing session variables available to the current script. It
allows you to store user-specific data across multiple pages.
Example:
php<?php
// Start or resume session
session_start();
// Set session variables
$_SESSION['username'] = 'John';
// Access session variables
echo $_SESSION['username']; // Outputs: John
?>
7. $_SERVER
$_SERVER
is an array containing information such as headers, paths, and script locations. It
provides server and execution environment information.
Example:
php<?php
echo $_SERVER['SERVER_NAME']; // Outputs the server's host name
echo $_SERVER['REMOTE_ADDR']; // Outputs the IP address of the user
?>
8. $_ENV
$_ENV
is an associative array containing environment variables available to the script. It's
populated from the environment under which the PHP parser is running.
Example:
php<?php
echo $_ENV['PATH']; // Outputs the system's PATH environment variable
?>