1. php
  2. /basics
  3. /global-variables

PHP Global variables

Definition

Superglobals are a special type of global variable that are always available, regardless of scope. They can be accessed from any function, class, or file without any extra effort. Some examples of these superglobals include GLOBALS, SERVER, REQUEST, POST, GET, FILES, ENV, COOKIE, and SESSION. Using these effectively can greatly enhance the functionality and efficiency of your PHP scripts.

Examples

Looking for a way to access global variables in PHP scripts from any place, even within functions or methods? Your go-to is the GLOBALS, an array where all global variables are tracked. Whenever you declare a variable, its name is included as an index in this array. Let's illustrate this with an example.

$x = 75;
$y = 25;
function addition() {
	$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;   // Output: 100

In this example, 'x' and 'y' are global variables accessed within a function using GLOBALS. 'z' is also a variable within the GLOBALS array, therefore available from outside the function.

The GLOBALS variable can be a complex beast to handle, especially because of its unique characteristic: prior to PHP 8.1, the GLOBALS array was always assigned by reference. This added a significant technical complexity when modifying the GLOBALS array, particularly when multiple global variables were affected at once.

However, since PHP 8.1, attempting certain mass changes to the GLOBALS array may throw fatal errors. Therefore, it's recommended to modify individual array elements as allowed.

foo = 'apple';
$myvars = $GLOBALS;
$myvars['foo'] = 'banana';
echo $foo;  // Output: banana

Fitfully using global variables and superglobals requires understanding their scope. In PHP, you can also use the global keyword outside a function. In fact, it's not an error if a file is included from inside a function.

In addition to global variables, there's another significant feature within PHP known as static variables. Unlike global variables, static variables exist only in a local function scope. They don't lose their value, even when the program execution leaves their scope. This feature makes them particularly useful for counting functions, that must not lose track of the current count.

function test() {
	static $a = 0;
	echo $a;
	$a++;
}

Key Takeaways

  • PHP global variables are accessible from any place within your PHP scripts, and all global variables are stored in an array named GLOBALS.

  • Superglobals in PHP are global variables that are always accessible, regardless of scope. These include GLOBALS, SERVER, REQUEST, POST, GET, FILES, ENV, COOKIE, and SESSION.

  • The GLOBALS array is a powerful but complex tool, as it was always assigned by reference prior to PHP 8.1. In newer versions, certain mass changes to the GLOBALS array may throw fatal errors.

  • Scope is crucial in working with global variables and superglobals in PHP. The global keyword can also be used outside of a function, and even when a file is included from within a function, it's not considered an error.

  • Static variables, another important feature within PHP, only exist in the local function scope, but maintain their value even when the program execution leaves their scope. This makes them particularly useful for counting functions.

List of built-in global variables:

PHP has several built-in global variables. Some of the most commonly used global variables include:

SuperglobalDescription
$_GETAn array that contains data passed to the script via the HTTP GET method.
$_POSTAn array that contains data passed to the script via the HTTP POST method.
$_SERVERAn array that contains information about the server and the current script, such as the server name, the client's IP address, and the script's file name.
$_SESSIONAn array that contains data that is stored across multiple page requests within a user's session.
$_COOKIEAn array that contains data passed to the script via HTTP cookies.
$_FILESAn array that contains information about files that have been uploaded to the server via the HTTP POST method.
$_ENVAn array that contains information about the environment variables set on the server.
$_REQUESTAn array that contains data passed to the script via both the GET and POST methods.
$_GLOBALSAn array that contains all global variables available to the script.
$GLOBALSA superglobal variable that contains all global variables available to the script, it is same as $_GLOBALS.

Additional Examples

<?php

// Declare a global variable
$global_variable = "Hello World";

// Function that uses the global variable
function myFunction() {
    global $global_variable;
    echo $global_variable;
}

// Function call
myFunction(); // Output: Hello World

?>

In this example, the variable $global_variable is declared outside of any function. The function myFunction() uses the global keyword to access this variable within the function. Without the global keyword, the function would not be able to access the variable and would produce an error.

Best Practices

  1. Try to avoid using global variables and instead pass variables as function arguments or use object-oriented programming techniques to access shared data.

  2. To make it clear which variables are global, it is best practice to declare them at the top of the script, before any functions or classes are defined.

  3. To make it easy to understand which variable is being used and for what purpose, it is important to use clear and descriptive variable names.

  4. To make it clear which variables are global, it is best practice to use a naming convention, such as prefixing global variables with the string "g_".

  5. The global keyword should be used with care, as it can make code difficult to understand and maintain.

  6. Be aware of the scope of global variables and the impact that changes to them can have on the rest of the script.

  7. If you have to use global variables use const or define to make sure that variables are read-only and cannot be changed.

  8. Superglobals like $_POST and $_GET should be used only in the scope they were intended for and not used as global variables.

Further Learning

Frequently Asked Questions about the PHP Global Variables

1. What is the global variable $_ files in PHP?

The global variable $_FILES in PHP is a superglobal array that is used to upload files from a client's computer to the server. It provides information about the files that have been uploaded via an HTTP POST request, typically through form submissions where the form's enctype attribute is set to multipart/form-data.

Each file uploaded to the server is represented as an array within the $_FILES array. This array contains several pieces of information about each file, including:

  • name: The original name of the file on the client machine. type: The MIME type of the file, if the browser provided this information. For instance, image/png.
  • tmp_name: The temporary filename of the file in which the uploaded file was stored on the server.
  • error: The error code associated with the file upload. This could be one of several predefined constants indicating whether the file uploaded successfully or if there was an error.
  • size: The size, in bytes, of the uploaded file.

You can access the information about uploaded files using this superglobal array. For example, if you have a file input field in a form with the name attribute set to userfile, you can access the name of the uploaded file using $_FILES['userfile']['name'].

Here's a simple example of how $_FILES might be used:

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["userfile"])) {
    $errors = $_FILES["userfile"]["error"];
    $fileName = $_FILES["userfile"]["name"];
    $fileTmpName = $_FILES["userfile"]["tmp_name"];
    $fileSize = $_FILES["userfile"]["size"];
    $fileType = $_FILES["userfile"]["type"];

    // Check for errors, process the file, etc.
}

This superglobal makes it easier to handle file uploads securely and effectively in PHP. However, it's essential to perform appropriate security checks, such as validating file types and sizes, to prevent vulnerabilities such as arbitrary file upload exploits.

2. What is the difference between global and local variable in PHP?

In PHP, variables can be categorized based on their scope, which determines where a variable can be accessed within a script. The main difference between global and local variables lies in their scope and accessibility.

  • Scope and Accessibility: Global variables are accessible throughout the script, while local variables are only accessible within the function they are defined in.
  • Lifespan: Global variables last until the script finishes executing, whereas local variables last only as long as the function execution takes.
  • Best Practices: Use global variables sparingly because they can lead to code that is difficult to debug and maintain. It's often better to pass variables as function arguments or return values to maintain clear and manageable scopes.
3. Is `$_cookie` a Superglobal variable?

Yes, $_COOKIE is a superglobal variable in PHP. Superglobals are built-in variables that are always accessible, regardless of scope, meaning they can be accessed from any function, class, or file without having to do anything special to access them.

The $_COOKIE superglobal array contains all the cookies that are sent by the client in the HTTP request. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can access and manipulate the cookies using this superglobal variable.

Each entry in the $_COOKIE array is identified by the cookie name and contains the value of the cookie. For example, if a cookie named "user" is set in the client's browser, you can access its value in your PHP script like so:

if(isset($_COOKIE['user'])) {
    echo 'User: ' . htmlspecialchars($_COOKIE['user']);
}

It's important to note that cookies are part of the HTTP header, so they must be sent before any output from your script (this is a common rule for all header operations in PHP). Additionally, when setting new cookies with setcookie() or modifying existing ones, the changes will only be visible in the $_COOKIE array on the next request that includes the updated cookies.

Remember, cookies are stored on the client-side and can be manipulated by the client or by anyone who can intercept the HTTP request. Therefore, sensitive information should not be stored directly in cookies, or if it is, it should be properly encrypted and secured.

4. Which is better: global variables or local variables in PHP?

The choice between global and local variables depends on your needs. If a variable's value will change across multiple functions, consider using local variables. However, when you need a persistently constant value, a global variable might be more appropriate.

5. Why should I use global variables in PHP?

Global variables in PHP offer flexibility as they can be accessed and modified anywhere throughout the PHP script, including within functions and across file boundaries. To declare such a variable, use the "global" keyword paired with your chosen variable name.

6. Where are PHP global variables stored?

PHP global variables are stored in what's commonly referred to as the "symbol table" or "global symbol table" for the PHP script's execution context. This table is an internal data structure used by the PHP engine to keep track of all the variables and their values that are currently defined in the global scope of the script. The symbol table ensures that variables are accessible by their names throughout the script's execution, wherever the global scope is applicable.

The superglobals, including $_GET, $_POST, $_COOKIE, $_FILES, $_ENV, $_REQUEST, $_SERVER, and $_SESSION (when sessions are started), are automatically populated by PHP at the beginning of each request and are stored in a way that makes them accessible in any scope without the need for the global keyword. These superglobals are part of the global scope but are treated specially by PHP due to their significance in handling input data, session data, server/environment information, and more.

7. How can I make a variable global in PHP?

You may declare a variable as global in PHP using two methods: either explicitly define it as global through the use of the 'global' keyword, or else employ the $GLOBALS syntax to refer to it.

8. What distinguishes a global variable from a local variable in PHP?

A global variable is defined outside of specific functions and can thus be accessed by any function within the program. Conversely, a local variable is confined to the function where it's declared, limiting its accessibility to that specific function only.

9. How can I clear global variables in PHP?

The unset() function is used to destroy specified variables in PHP. Be aware that the behavior of unset() may vary inside functions based on the type of variable being dealt with. Unsetting a global variable inside a function only destroys its locally scoped counterpart.