Global Variables & Superglobals

Last updated on

Variables in PHP are general elements used for data storage and other manipulations. Global variables belong to a particular category of variables accessible within different scopes of a PHP application. Meanwhile, superglobals are built-in global arrays that are always accessible from any part of a PHP script.

So, A global variable in PHP is declared outside any function or method, and by default, it is visible from anywhere in the script unless some limitations restrict this accessibility. This flexibility comes in handy when you need consistent access to the same data across different functions or parts of your program.

Global variables can be a bit of a pain, especially when trying to write neat, concise code. The upside is that they make life easier as they act as a single point of reference for values with importance to different parts of your script. Such variables, depending on the approach one intends to take, can either be assigned using the global keyword or by using PHP's superglobals, which we shall explain in detail.

Next is the section on the global keyword, which allows access to and modification of variables that are defined outside a function from within its scope.

Using the Keyword of Global variables in PHP

The global keyword in PHP brings any global variable into the scope of a function. Usually, a variable declared outside a function is not accessible inside it. By declaring it as global, you allow functions to reference external variables without having to redefine them. Here is a simple example of this:


$globalVar = "Hello, World!";

function showGlobalVar() {
    global $globalVar;
    echo $globalVar;
}

showGlobalVar(); // Outputs: Hello, World!

In the code above, $globalVar is a global variable. By using global $globalVar; inside the function, we’re pulling it into the function’s scope, allowing the function to access $globalVar without redeclaring it. While this approach is straightforward, keep in mind that relying heavily on global variables can make your code harder to manage. Tracking the values of global variables across multiple functions becomes challenging, especially as your application grows in complexity.  

In the following section, you will learn superglobals—built-in global variables available in all scopes that offer unique functions for handling data.

Understanding PHP Superglobals

In PHP, superglobals are a set of predefined variables that have direct access to some types of script data. Unlike ordinary globals, superglobals can be accessed from anywhere inside the code—be it within functions, methods, or classes—without using the global keyword.

They include a wide range of common tasks, such as handling form input data, session information, and server details.

PHP superglobals are arrays that include, but are not limited to, $_GET, $_POST, $_SESSION, $_COOKIE, $_SERVER, and $_ENV. Each of the aforementioned superglobals has its role in carrying out certain tasks without necessarily having to handle complex processing.

An example could be using $_GET and $_POST when dealing with data from HTML forms, while $_SESSION and $_COOKIE handle user session data and persistent information, respectively.

Anyway, here is a table shows you a list of superglobal variables:

$GLOBALSAccesses global variables across PHP files.
$_SERVERHolds server/environment info, like headers, paths, and script locations.
$_ENVStores environment variables accessible during runtime.
$_SESSIONManages user session data across multiple pages.
$_REQUESTRetrieves data from GET, POST, and COOKIE.
$_GETGets data from URL query strings.
$_POSTCollects data sent in POST requests.
$_FILESManages file uploads in form submissions.
$_COOKIEStores small data on the client for state tracking.

In the next few sections, we take a closer look at some of these superglobals and how you might use them in different contexts.

Working with PHP Superglobals: $_GET and $_POST

$_GET and $_POST are two PHP superglobals specifically designed to handle form data. You'll be using these arrays quite repeatedly to capture the values of input fields that users fill out on your site and then submit.  

  • $_GET: This superglobal collects input from the query string of the URL. It is good to use when the information should not be private, such as search terms or filtering options. Since this data is part of the URL, $_GET can be accessed by a simple link with no need for a form submission.
  • $_POST: In contrast, $_POST contains the data sent through HTTP POST requests. It’s used appropriately for sensitive data—passwords and other personal data—since it doesn’t show the data in the address bar.

The following example illustrates using the $_POST superglobal to retrieve data from a form:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['name'];
    echo "Hello, " . htmlspecialchars($name);
}

In this example, $_POST retrieves the value from the name input field of a form, and we output it with a simple greeting. The htmlspecialchars() function helps prevent cross-site scripting (XSS) attacks by escaping HTML characters.

We will now explain the two most important superglobals, $_SESSION and $_COOKIE, responsible for storing and accessing user-specific data in the following section.

Both $_SESSION and $_COOKIE allow you to save information that will be preserved across multiple pages, with one distinction: sessions store information on the server while cookies store it on the user's computer.  

$_SESSION: This superglobal is used to store user data on the server side. It’s highly useful when you want data to persist throughout a user’s session but only for that session; for example, tracking whether or not a user has logged in.  

Here is an example:

session_start();
$_SESSION['username'] = "JohnDoe";
echo "Session username is: " . $_SESSION['username']; 

$_COOKIE: Cookies stored on the client’s side allow data to persist beyond a single session. You might store something like user preferences or more information about a user for tracking in $_COOKIE.  

Here is an example:

setcookie("user", "JohnDoe", time() + (86400 * 30), "/"); // 86400 = 1 day
if(isset($_COOKIE["user"])) {
    echo "Cookie username is: " . $_COOKIE["user"];
}

Using sessions and cookies together can be a potent way of managing user data. However, it is very important to manage these sessions and cookies carefully; poor handling of session data or cookies can expose your application to security risks.

Next, we will look into $_SERVER and $_ENV: superglobals allowing access to server information and environment information.

Displaying Server and Environment Information with $_SERVER and $_ENV

The superglobal $_SERVER contains a lot of handy information about your server and the execution environment—everything from server headers to file paths. It's an associative array containing several server-level values useful in many different situations, anything from debugging to delivering responses customized to the server's configuration.  

You might use $_SERVER['HTTP_USER_AGENT'], for example, to retrieve information about the user's browser, or $_SERVER['REMOTE_ADDR'] to get the user's IP address: 

echo "User IP Address: " . $_SERVER['REMOTE_ADDR'];
echo "User Browser: " . $_SERVER['HTTP_USER_AGENT'];

Meanwhile, $_ENV allows access to environment variables. These are most often used when you want to retrieve configuration values or sensitive data, which should not appear anywhere in your codebase.

This superglobal allows you to work with different settings for development and production environments. Although less widely used than some of the other superglobals, $_ENV can still be an essential element in developing both secure and flexible applications.

At the end of this section, we summarize the most important things to pay attention to and best practices when working with PHP globals and superglobals.

Wrapping Up

In this tutorial, we reviewed global variables and superglobals in PHP, including the global keyword and superglobals like $_GET, $_POST, $_SESSION, $_COOKIE, $_SERVER, and $_ENV. These allow a PHP developer to efficiently handle data across different parts of an application, whether handling user input, maintaining session data, or retrieving server information.

Here are some best practices to make the most out of global variables and superglobals in your projects:

  • Use global variables only when necessary to avoid complicating code maintenance.
  • Sanitize input from $_GET and $_POST for security reasons.
  • Make best use of sessions and cookies with a judicious balance between data persistence and privacy.
  • Use $_SERVER for server data only where you have to; avoid it if possible to prevent leakage of sensitive information.
  • Use $_ENV for handling configurations to avoid storing sensitive information directly in the main code.

These practices fundamentally help in the development of capabilities of your PHP work, making it more functional and secure. This will help you write more organized, efficient, and safer code, making global variables and superglobals one of the most valuable parts of your PHP toolkit.

To see more tutorials for PHP, click here.  

Frequently Asked Questions (FAQs)

  • What are global variables in PHP?

    Global variables in PHP are variables declared outside any function or method, making them accessible from any part of the script. They’re especially useful when you need consistent access to the same data across different functions or areas of your program.
  • How do you declare a global variable in PHP?

    To declare a global variable, simply define it outside any function or class. You can then use it inside functions by declaring it as global with the global keyword.
    Example:
    $globalVar = "Hello World!";
    function displayVar() {
        global $globalVar;
        echo $globalVar;
    }
    displayVar(); // Outputs: Hello World!
    
  • What is the difference between global and superglobal in PHP?

    A global variable requires the global keyword to be accessed inside functions, whereas superglobals like $_GET, $_POST, $_SESSION are accessible anywhere in the script without needing global. Superglobals are built-in arrays that handle specific types of data, such as form input or session info.
  • How do I use $_GET and $_POST in PHP?

    $_GET and $_POST are superglobals used to retrieve data from forms. $_GET fetches data from the URL query string, while $_POST handles form data sent via POST requests.
    Example:
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $name = $_POST['name'];
        echo "Hello, " . htmlspecialchars($name);
    }
  • What is $_SESSION in PHP?

    $_SESSION is a superglobal array that stores data on the server for individual user sessions. It's useful for tracking login status or user-specific data.
    Example:
    session_start();
    $_SESSION['username'] = "JohnDoe";
    echo "Username: " . $_SESSION['username'];
    
  • Can global variables create issues in PHP?

    Yes, extensive use of global variables can lead to hard-to-maintain code. It becomes challenging to track values across different functions, especially in larger applications. Using too many globals can make debugging and testing difficult.
  • What is $_SERVER used for in PHP?

    $_SERVER is a superglobal that holds information about the server and execution environment. It includes data like headers, paths, and script locations.
    Example:
    echo "User IP Address: " . $_SERVER['REMOTE_ADDR'];
    echo "User Browser: " . $_SERVER['HTTP_USER_AGENT'];
    
  • When should I use $_COOKIE in PHP?

    Use $_COOKIE when you want to store data on the client’s browser, like user preferences, that persists across multiple sessions.
    Example:
    setcookie("user", "JohnDoe", time() + (86400 * 30), "/");
    if(isset($_COOKIE["user"])) {
        echo "User: " . $_COOKIE["user"];
    }
    
Share on: