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

PHP Global variables


Superglobals are PHP global variables always accessible regardless of scope, enhancing script functionality and efficiency. Examples include $GLOBALS, $_SERVER, $_REQUEST, $_POST, $_GET, $_FILES, $_ENV, $_COOKIE, and $_SESSION.


Access global variables in PHP scripts from anywhere using $GLOBALS, an array tracking all global variables. Here's how:

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

In PHP 8.1 and beyond, modifying the $GLOBALS array requires caution as certain changes may cause fatal errors. Here’s an adjusted approach:

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

Global variables and superglobals require understanding their scope. PHP also features static variables, which retain their value across function calls, ideal for counting functions:

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

Key Takeaways

  • Superglobals and global variables are always accessible within PHP scripts.

  • Scope understanding is crucial for effective use.

  • Static variables offer persistent values within local scopes.

Built-in Global Variables:

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

$_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


// 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. Minimize global variable use, preferring function arguments or object-oriented methods for shared data access.
  2. Declare global variables at the script's top and use descriptive names for clarity.
  3. Consider global variables' scope and impact carefully, using constants for immutability when possible.

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.