Lesson 31 of 50 – PHP Superglobals
62%

PHP Superglobals

PHP superglobals are predefined variables that are available throughout a PHP script. They can be accessed inside functions without declaring them as global variables.

The main PHP superglobals are:

  • $GLOBALS
  • $_SERVER
  • $_GET
  • $_POST
  • $_FILES
  • $_COOKIE
  • $_SESSION
  • $_REQUEST
  • $_ENV
1. What Are Superglobals?

Superglobals are built-in PHP variables that are available in all scopes. You can use them inside functions without writing the global keyword.

<?php
$name = "Rahul";

function showStudent() {
    echo $_SERVER['PHP_SELF'];
}

showStudent();
?>

This example displays the current script path. The exact output depends on the requested URL.

Superglobals are especially useful when working with form submissions, server information, sessions, cookies, and uploaded files.

2. The $GLOBALS Superglobal

The $GLOBALS array provides access to variables in the global scope.

<?php
$first = 10;
$second = 20;

function calculateSum() {
    $GLOBALS['total'] =
        $GLOBALS['first'] + $GLOBALS['second'];
}

calculateSum();

echo $total;
?>
Output:
30

The function reads $first and $second from the global scope and creates the global variable $total.

Although useful, passing values through function parameters and returning results is often easier to maintain.

3. The $_SERVER Superglobal

The $_SERVER array contains information about the server and the current request.

<?php
echo "Script Name: " . $_SERVER['PHP_SELF'];
echo "<br>";

echo "Request Method: " . $_SERVER['REQUEST_METHOD'];
echo "<br>";

echo "Server Name: " . $_SERVER['SERVER_NAME'];
?>

Example output for a local request might be:

Script Name: /php_tutorials/example.php
Request Method: GET
Server Name: localhost

Actual values depend on the server configuration, URL, and request method.

Common $_SERVER keys:

  • PHP_SELF – path of the current script.
  • REQUEST_METHOD – method used for the request.
  • SERVER_NAME – server host name.
  • HTTP_USER_AGENT – user-agent header, if provided.
  • REMOTE_ADDR – address of the connecting client, which may be a proxy.

Treat request-derived values as untrusted. Escape values before displaying them in HTML.

4. The $_GET Superglobal

The $_GET array contains values supplied through URL query parameters.

Example URL:

http://localhost/example.php?name=Rahul&city=Patna

PHP code:

<?php
$name = $_GET['name'] ?? '';
$city = $_GET['city'] ?? '';

echo "Name: " . htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
echo "<br>";
echo "City: " . htmlspecialchars($city, ENT_QUOTES, 'UTF-8');
?>
Output:
Name: Rahul
City: Patna

The ?? operator provides an empty string if the requested key is missing or its value is null.

GET parameters appear in the URL, so do not use them for passwords or other sensitive information.

5. The $_POST Superglobal

The $_POST array contains form values submitted using the HTTP POST method when the form uses a supported encoding.

Example form:

<form method="post" action="">
    <label for="studentName">Enter Name:</label>
    <input type="text" id="studentName" name="student_name" required>

    <button type="submit">Submit</button>
</form>

PHP code on the same page:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['student_name'] ?? '');

    if ($name !== '') {
        echo "Welcome, " .
            htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
    } else {
        echo "Please enter your name.";
    }
}
?>

If the user enters Rahul, the page displays:

Welcome, Rahul

POST does not automatically make submitted information secure. Validate input on the server, use HTTPS, and apply CSRF protection to state-changing forms where appropriate.

6. The $_FILES Superglobal

The $_FILES array contains information about files uploaded through an HTML form.

Example form:

<form method="post" enctype="multipart/form-data">
    <label for="myFile">Choose a file:</label>
    <input type="file" id="myFile" name="myFile" required>

    <button type="submit">Upload</button>
</form>

PHP code:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (
        isset($_FILES['myFile']) &&
        $_FILES['myFile']['error'] === UPLOAD_ERR_OK
    ) {
        echo "Uploaded file: " .
            htmlspecialchars(
                $_FILES['myFile']['name'],
                ENT_QUOTES,
                'UTF-8'
            );
    } else {
        echo "File upload failed.";
    }
}
?>

This example only displays the uploaded filename. It does not save the file permanently.

Before saving uploaded files, validate their type and size, generate a safe server-side filename, and store them in an appropriately configured directory. Do not trust the original filename or extension alone.

7. The $_COOKIE Superglobal

The $_COOKIE array reads cookies sent by the browser with the current request.

A cookie must be set before output is sent to the browser.

<?php
setcookie(
    'student_name',
    'Rahul',
    [
        'expires' => time() + 3600,
        'path' => '/',
        'secure' => !empty($_SERVER['HTTPS']),
        'httponly' => true,
        'samesite' => 'Lax'
    ]
);
?>

After the browser receives and sends the cookie back on a subsequent request, it can be read using:

<?php
$name = $_COOKIE['student_name'] ?? '';

if ($name !== '') {
    echo htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
} else {
    echo "Cookie is not available yet.";
}
?>

The first request that sets the cookie normally cannot read that new cookie through $_COOKIE until the browser sends it back in a later request.

Cookie options should be selected according to your application's security requirements. HTTPS should be used for production websites.

8. The $_SESSION Superglobal

The $_SESSION array stores data across requests using PHP's session mechanism. Call session_start() before accessing session data and before sending output.

Store a session value:

<?php
session_start();

$_SESSION['student_name'] = 'Rahul';

echo "Session value saved.";
?>
Output:
Session value saved.

Read the session value on another request:

<?php
session_start();

$name = $_SESSION['student_name'] ?? '';

if ($name !== '') {
    echo "Welcome, " .
        htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
} else {
    echo "No student session found.";
}
?>

If the session value exists, the page displays Welcome, Rahul.

For login systems, configure sessions securely, regenerate the session ID after authentication, and remove session data when logging out.

9. The $_REQUEST and $_ENV Superglobals
The $_REQUEST Superglobal

The $_REQUEST array may contain values from GET, POST, and COOKIE data. Its exact contents depend on the PHP configuration.

<?php
$name = $_REQUEST['name'] ?? '';

echo htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
?>

Because the source of a value can be unclear, using $_GET or $_POST explicitly is usually preferable.

The $_ENV Superglobal

The $_ENV array can contain environment variables made available to PHP. Its contents depend on the server and PHP configuration.

<?php
$appEnvironment = $_ENV['APP_ENV'] ?? 'not set';

echo "Environment: " .
    htmlspecialchars(
        $appEnvironment,
        ENT_QUOTES,
        'UTF-8'
    );
?>

If the variable is not available in $_ENV, the example displays not set. Some applications read environment variables using getenv() instead.

Practice Assignments
  1. Display the current script path using $_SERVER.
  2. Create a GET form that accepts a student's name.
  3. Create a POST form that accepts a student's name and city.
  4. Display a value from a global variable using $GLOBALS.
  5. Read and display a cookie after the browser sends it back.
  6. Store and read a student name using sessions.
  7. Build a file-upload form and display the uploaded filename safely.
  8. Check the request method using $_SERVER['REQUEST_METHOD'].
  9. Read an environment variable with a fallback value.

🧠 Quick Quiz

1. Which superglobal contains GET query parameters?




2. Which function starts or resumes a PHP session?




3. Which superglobal contains uploaded file information?