Superglobal Variables in PHP with Examples

The variables that are predefined in PHP are known as superglobal variables. These predefined or built-in variables are always accessible, regardless of scope (global or local).

Therefore, you can access them from any part of the program such as functions, classes, and so on. In short, superglobals are automatically available for all the scopes as its global and do not require any keyword to declare it global explicitly.

Superglobal variables are specially built-in associative arrays in PHP, designed to hold various types of data, such as user input, server information, environment variables, session data, and more. They are automatically available in all scopes throughout a script.

List of Superglobal Variables in PHP


The list of commonly used superglobal variables with their description in PHP are as follows:

  • $GLOBALS
  • $_SERVER
  • $_REQUEST
  • $_POST
  • $_GET
  • $_COOKIE
  • $_SESSION
  • $_FILES
  • $_ENV

$GLOBALS:

The $_GLOBALS superglobal is an associative array that holds references to all global variables in the global scope. PHP stores all the global variables in an associative array with the help of $_GLOBALS[name of the variable].


Example 1:

<?php
$site_name = "Scientech Easy"; // Global variable

function displaySiteName() {
// Accessing global variable using $_GLOBALS
echo "Welcome to " . $GLOBALS['site_name'];
}
// Calling the function.
displaySiteName();
?>
Output: 
      Welcome to Scientech Easy

In this example, we have defined a global variable named $site_name and assigned it a string value. Then, we have defined a displaySiteName() function in which we have accessed the global variable $site_name using the $GLOBALS superglobal.

$_SERVER:

The super global $_SERVER variable is an array that contains the information about the server environment, such as headers, paths, and script locations. It is commonly used to obtain server and execution environment details.

PHP creates the $_SERVER superglobal array and stores various server and execution environment information in it, as provided by the web server.


Example 2:

<?php
echo "Server Name: " . $_SERVER['SERVER_NAME'] . "<br>";
echo "Script Filename: " . $_SERVER['SCRIPT_FILENAME'] . "<br>";
echo "Request Method: " . $_SERVER['REQUEST_METHOD'] . "<br>";
echo "Host Header: " . $_SERVER['HTTP_HOST'] . "<br>";
echo "User Agent: " . $_SERVER['HTTP_USER_AGENT'] . "<br>";
?>
Output:
     Server Name: localhost
     Script Filename: D:\xampp\htdocs\PHP_Project\index.php
     Request Method: GET
     Host Header: localhost:8000
     User Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)

In this example,

  • $_SERVER[‘SERVER_NAME’] returns the server or host name. $_SERVER[‘SCRIPT_FILENAME’] returns the absolute path of the script.
  • $_SERVER[‘REQUEST_METHOD’] returns the request method used to access the page.
  • $_SERVER[‘HTTP_HOST’] returns the host header in the current HTTP request.
  • $_SERVER[‘HTTP_USER_AGENT’] returns the user agent of the user.

$_POST

The superglobal variable $_POST is an associative array in PHP that is used to collect data submitted by an HTML form with the help of HTTP POST method. We commonly use ti for sending sensitive or large amounts of data.

Let’s take an example in which we will use $_POST superglobal variable to access data submitted by a form. We will create two files named “index.php” and “submit.php”. The index.php file will contain the HTML form. The submit.php file will handle the form submission.


Example 3:

index.php File 

<form method="post" action="submit.php">
    <input type="text" name="email" placeholder="Enter your email">
    <input type="submit" value="Subscribe">
</form>

submit.php File

<?php
// submit.php
if (isset($_POST['email'])) {
    echo "Subscription email: " . htmlspecialchars($_POST['email']);
}
?>

Save the above both files inside the same folder you created. Start the server. Enter an email in the form input and click the “Subscribe” button. This will send a POST request to submit.php. The output will be as:

Output:
      Subscription email: contact@scientecheasy.com

In this example, $_POST[’email’] retrieves the email entered by the user in the form.

$_GET:

Like $_POST, the superglobal variable $_GET is also an associative array in PHP that is used to collect the data submitted by an HTML form through the HTTP GET method. It is often used to pass data through URLs.

The data sent through the HTTP GET method is appended to the URL in the HTTP request and is visible in the web browser’s address bar. This means that any data submitted using the GET method can be seen in the URL, which makes it less secure for transmitting sensitive data, like passwords.

Let’s take an example in which we will use the $_GET superglobal variable to access data submitted by a form. We will create two files named “index.php” and “profile.php”. The index.php file will contain the HTML form. The profile.php file contains the PHP code to handle and display the user parameter passed in the URL from the index.php page.

Example 4:

index.php File:

<a href="profile.php?user=JohnDoe">View Profile</a>

profile.php File:

<?php
// profile.php
// Check if the 'user' parameter exists in the GET request
if (isset($_GET['user'])) {
// Display the user parameter value in a safe way using htmlspecialchars.
   echo "Profile of: " . htmlspecialchars($_GET['user']);
} else {
// Display a message if no user parameter is provided in the URL.
   echo "No user specified.";
}
?>

$_COOKIE:

The super global variable $_COOKIE in PHP is used to access cookie data. Cookies are small data files sent by the web server and stored in the user’s browser. They are mainly used to track the user behavior for analysis purpose.

Each cookie has a name and value. You can access the value of cookie using the $_COOKIE[“cookie_name”]. Here is a simple example of how to create a cookie and access its value in PHP.

Example 5:

<?php
$cookie_name = "user";
$cookie_value = "JohnDoe";
// Set a cookie for 30 days
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day

// Check if the cookie is set
if (!isset($_COOKIE[$cookie_name])) {
   echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
   echo "Cookie '" . $cookie_name . "' is set!" . "\n";
   echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
Output:
     Cookie named 'user' is not set!

In this code, we are defined setcookie() function to create a cookie named “user” with value “JohnDoe”. The cookie is set to expire in 30 days. Then, we have used the if-else statement to check the cookie is set using isset($_COOKIE[$cookie_name]). If set, it will display the name and value of the cookie on the console.

$_SESSION:

The superglobal variable $_SESSION is used to store session data. Session data is not stored in the user’s computer but on the web server.

The session is started with the session_start() function provided by PHP, and the session information is stored in the $_SESSION superglobal associative array. This is a built-in PHP superglobal array that stores all the session data.

A session is used to track a user’s login so that the user can navigate across multiple pages on the site without having to log in again on each web page.

Let’s take an example in which we will use $_SESSION superglobal variable to store and access session data in PHP.

Example 6:

<?php
// Start the session
session_start();

// Store session data
$_SESSION["username"] = "JohnDoe";
$_SESSION["email"] = "john@example.com";

// Access session data
echo "Username: " . $_SESSION["username"] . "\n";
echo "Email: " . $_SESSION["email"];
?>
Output:
      Username: JohnDoe
      Email: john@example.com

In this example, we have used the session_start() function to begin a new session or resume an existing session. Next, we have created two session variables, username and email, using the $_session array. Finally, we have accessed the session variables and displayed them on the console.

Here, we have explained only seven superglobal variables in PHP in brief with the help of simple examples. You will learn more about superglobals in the further tutorials one by one as these are the part of arrays in PHP.