Global Variables & Superglobals
Last updated onVariables 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,
is a global variable. By using $globalVar
inside the function, we’re pulling it into the function’s scope, allowing the function to access global $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. $globalVar
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:
$GLOBALS | Accesses global variables across PHP files. |
$_SERVER | Holds server/environment info, like headers, paths, and script locations. |
$_ENV | Stores environment variables accessible during runtime. |
$_SESSION | Manages user session data across multiple pages. |
$_REQUEST | Retrieves data from GET, POST, and COOKIE. |
$_GET | Gets data from URL query strings. |
$_POST | Collects data sent in POST requests. |
$_FILES | Manages file uploads in form submissions. |
$_COOKIE | Stores 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
and $_GET
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. $_POST
: 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.$_GET
: In contrast,$_POST
$_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,
retrieves the value from the name input field of a form, and we output it with a simple greeting. The $_POST
function helps prevent cross-site scripting (XSS) attacks by escaping HTML characters.htmlspecialchars()
We will now explain the two most important superglobals,
and $_SESSION
, responsible for storing and accessing user-specific data in the following section.$_COOKIE
Using $_SESSION and $_COOKIE for Data Persistence
Both
$_SESSION
and
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. $_COOKIE
: 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. $_SESSION
Here is an example:
session_start();
$_SESSION['username'] = "JohnDoe";
echo "Session username is: " . $_SESSION['username'];
: 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
. $_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
and $_SERVER
: superglobals allowing access to server information and environment information.$_ENV
Displaying Server and Environment Information with $_SERVER and $_ENV
The superglobal
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. $_SERVER
You might use
, for example, to retrieve information about the user's browser, or $_SERVER['HTTP_USER_AGENT']
to get the user's IP address: $_SERVER['REMOTE_ADDR']
echo "User IP Address: " . $_SERVER['REMOTE_ADDR'];
echo "User Browser: " . $_SERVER['HTTP_USER_AGENT'];
Meanwhile,
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. $_ENV
This superglobal allows you to work with different settings for development and production environments. Although less widely used than some of the other superglobals,
can still be an essential element in developing both secure and flexible applications.$_ENV
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
, and $_SERVER
. 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.$_ENV
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
and$_GET
for security reasons.$_POST
- Make best use of sessions and cookies with a judicious balance between data persistence and privacy.
- Use
for server data only where you have to; avoid it if possible to prevent leakage of sensitive information.$_SERVER
- 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?
How do you declare a global variable in PHP?
What is the difference between global and superglobal in PHP?
How do I use $_GET and $_POST in PHP?
What is $_SESSION in PHP?
Can global variables create issues in PHP?
What is $_SERVER used for in PHP?
When should I use $_COOKIE in PHP?