Skip to main content
PHP for Beginners
CHAPTER 18 Beginner

PHP Superglobals

Updated: May 12, 2026
20 min read

# Chapter 18: PHP Superglobals

1. Introduction

Welcome to Chapter 18! Throughout the course, we have been using variables like $POST, $GET, and $SESSION without fully explaining what they actually are. These are known as Superglobals. In PHP, superglobals are built-in arrays that are always accessible, regardless of scope. You can access them from any function, class, or file without needing to pass them as parameters. In this chapter, we will summarize the superglobals we know and introduce the powerful $SERVER and $FILES arrays.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define what a Superglobal is in PHP.
  • Review the use cases for $GET, $POST, $SESSION, and $COOKIE.
  • Extract server and request information using the $SERVER array.
  • Prepare HTML forms for file uploads using enctype.
  • Briefly introduce the $_FILES array.

3. What are Superglobals?

In Chapter 9, we learned about Variable Scope. Variables defined outside a function cannot be accessed inside a function unless passed as an argument. Superglobals break this rule. They are universally accessible anywhere in your script automatically.
php
123456789101112
<?php
$name = "Global John"; // Standard global variable

function testScope() {
    // echo $name; // ERROR!
    
    // Superglobals work fine!
    if(isset($_POST[&#039;name'])) {
        echo $_POST[&#039;name']; 
    }
}
?>

4. The Core Four (Review)

  1. 1. $GET: An associative array of variables passed to the current script via the URL parameters.
  1. 2. $POST: An associative array of variables passed to the current script via the HTTP POST method (invisible form data).
  1. 3. $SESSION: An associative array of variables stored on the server tied to the user's specific session ID.
  1. 4. $COOKIE: An associative array of variables stored on the user's local browser and sent with the HTTP request.

5. The $SERVER Superglobal

The $SERVER array holds vital information about HTTP headers, paths, and script locations. It is populated directly by the web server (Apache/Nginx).

Commonly used $SERVER keys:

  • $SERVER['PHPSELF']: The filename of the currently executing script (useful for form actions).
  • $SERVER['SERVERNAME']: The name of the host server (e.g., localhost or www.example.com).
  • $SERVER['HTTPHOST']: The Host header from the current request.
  • $SERVER['HTTPUSERAGENT']: Identifies the user's browser and operating system.
  • $SERVER['REMOTEADDR']: The IP address of the user viewing the page.
  • $SERVER['REQUESTMETHOD']: Returns the request method used (GET, POST, PUT, DELETE).

php
1234
<?php
echo "You are accessing this from IP: " . $_SERVER[&#039;REMOTE_ADDR'] . "<br>";
echo "You are using browser: " . $_SERVER[&#039;HTTP_USER_AGENT'];
?>

6. The $FILES Superglobal (Preview)

When a user uploads an image or a document via an HTML form, the data does NOT go into $POST. It goes into the $_FILES superglobal.

To upload files, your HTML <form> MUST include the attribute enctype="multipart/form-data".

html
1234
<form action="upload.php" method="POST" enctype="multipart/form-data">
    Select image: <input type="file" name="profile_pic">
    <button type="submit">Upload</button>
</form>

When submitted, $FILES['profilepic'] will contain an array of data about the uploaded file, including its temporary location on the server, its size, and its original name. We will build a complete upload system in Chapter 24.

7. Real-World Examples

Imagine building a security logging system. When someone attempts to log in, you want to record exactly who they are, what browser they are using, and what page they tried to access.
php
123456789101112
<?php
// security_log.php
$ip = $_SERVER[&#039;REMOTE_ADDR'];
$browser = $_SERVER[&#039;HTTP_USER_AGENT'];
$page_accessed = $_SERVER[&#039;PHP_SELF'];
$method = $_SERVER[&#039;REQUEST_METHOD'];

$log_entry = "[$method] Request on $page_accessed from IP: $ip using $browser \n";

// Write to a log file
file_put_contents("access.log", $log_entry, FILE_APPEND);
?>

8. Output Explanations

If you visit securitylog.php, the server populates the $SERVER array. The script pulls the IP address (127.0.0.1 for localhost), the User Agent string (which might be Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/114.0...), and the method (GET). It formats this into a string and securely appends it to access.log using the FILEAPPEND flag.

9. Common Mistakes

  • Trusting $SERVER['HTTPUSERAGENT']: The user agent string is sent by the browser. A malicious user can fake (spoof) their user agent to say anything they want. Do not use it for critical security checks.
  • Forgetting enctype for files: If you try to upload a file via POST but forget enctype="multipart/form-data", $FILES will be empty, and PHP will just put the filename text into $POST.
  • Misusing $SERVER['PHPSELF'] in forms: echo $SERVER['PHPSELF']; inside a form action can be exploited in Cross-Site Scripting (XSS) attacks. Always wrap it in htmlspecialchars().

10. Best Practices

  • When submitting a form back to the exact same page, use action="<?php echo htmlspecialchars($SERVER['PHPSELF']); ?>".
  • You can inspect the entire $SERVER array by wrapping printr($SERVER) in <pre> tags to see all the data your server provides!

11. Exercises

  1. 1. Write a script that checks $SERVER['REQUESTMETHOD']. If it is "GET", echo "This is a GET request".
  1. 2. Use printr($_SERVER) inside <pre> tags to explore your local server's configuration.

12. Mini Project: User Dashboard & Environment Inspector

Task: Build a page that simulates a user dashboard, displaying environmental information dynamically from the superglobals.
php
123456789101112131415161718192021222324252627282930313233343536
<?php
session_start();
// Simulate a logged-in user
$_SESSION[&#039;username'] = "Developer_01";
?>

<!DOCTYPE html>
<html>
<head>
    <title>Dashboard Info</title>
    <style>
        body { font-family: Arial; }
        .box { background: #f9f9f9; padding: 15px; border-left: 5px solid #007BFF; margin-bottom: 20px; }
    </style>
</head>
<body>
    <h2>System Information Dashboard</h2>
    
    <div class="box">
        <h3>Session Data</h3>
        <p>Logged in as: <strong><?php echo $_SESSION[&#039;username']; ?></strong></p>
    </div>

    <div class="box">
        <h3>Network Data</h3>
        <p>Your IP Address: <strong><?php echo $_SERVER[&#039;REMOTE_ADDR']; ?></strong></p>
        <p>Server Software: <strong><?php echo $_SERVER[&#039;SERVER_SOFTWARE']; ?></strong></p>
        <p>Current Script Path: <strong><?php echo $_SERVER[&#039;PHP_SELF']; ?></strong></p>
    </div>

    <div class="box">
        <h3>Browser Data</h3>
        <p>User Agent: <strong><?php echo $_SERVER[&#039;HTTP_USER_AGENT']; ?></strong></p>
    </div>
</body>
</html>

13. Coding Challenges

Challenge 1: Create a form with a single text input. The form should submit to itself using POST. Write a PHP if statement using $SERVER['REQUESTMETHOD'] to check if the form was submitted. If it was, safely echo the data from $POST.

14. MCQs with Answers

1. What defines a PHP Superglobal? A) It is an array that only contains numerical data. B) It is a built-in variable that is always accessible, regardless of scope. C) It is a variable that is shared between different websites. D) It is an array that stores database passwords. *Answer: B*

2. Which superglobal holds the IP address of the visitor? A) $GET['IP'] B) $SESSION['USERIP'] C) $SERVER['REMOTEADDR'] D) $NETWORK['IP'] *Answer: C*

3. What HTML form attribute is strictly required to populate the $FILES superglobal? A) method="FILES" B) enctype="multipart/form-data" C) upload="true" D) action="upload.php" *Answer: B*

15. Interview Questions

Q: Name 5 PHP Superglobals. *A:* $GET, $POST, $SESSION, $COOKIE, and $SERVER. (Others include $FILES, $REQUEST, $ENV, and $GLOBALS).

Q: What is the $REQUEST superglobal? *A:* $REQUEST is an array that automatically contains the contents of $GET, $POST, and $COOKIE. While it seems convenient, it is highly recommended NOT to use it for security reasons. You should always be explicit about where you expect data to come from (e.g., explicitly reading $POST for a form submission).

16. FAQs

Q: Can I create my own superglobal? *A:* You cannot create native superglobals like $POST, but you can use the $GLOBALS array to make a variable universally accessible (e.g., $GLOBALS['mysetting'] = true;). However, relying heavily on global variables is considered bad practice in modern architecture.

17. Summary

You've unlocked the backend environment! You learned that Superglobals are universally accessible arrays that manage the flow of data across the web. You reviewed how forms and sessions use them, and explored how the $_SERVER array gives you deep insights into the server environment, user network, and HTTP request headers.

18. Next Chapter Recommendation

We have written a lot of procedural code (code that runs top-to-bottom). However, professional web applications are built using a completely different paradigm. In Chapter 19: PHP Object-Oriented Programming Basics, we will shift our mindset and learn how to model our code after real-world objects!

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·