PHP: Superglobals — $_GET and $_POST

You're now standing right at the boundary between the server and the browser. Superglobals are PHP's built-in delivery packages — every request, the browser bundles up user data and sends it over; PHP unwraps it into these variables, ready to use anywhere in your script.

1. What Are Superglobals?

Superglobals are PHP's built-in variables that are accessible from any scope without needing the global keyword. They all start with $_ and are always available.

Superglobal Holds Common Use
$_SERVER Server and execution environment info Get current URL, detect HTTPS
$_GET URL query parameters Pagination ?page=2, search ?q=PHP
$_POST Form data sent via POST Login credentials, registrations
$_FILES Uploaded file data Avatar uploads
$_COOKIE Browser-side cookies "Remember me" feature
$_SESSION Server-side session data Login state persistence

2. $_SERVER

$_SERVER is an array packed with server and request-level information:

PHP
<?php
// Basic info
echo $_SERVER['REQUEST_METHOD'];    // GET or POST
echo $_SERVER['REQUEST_URI'];       // /myphp/page.php?id=1
echo $_SERVER['HTTP_HOST'];         // localhost
echo $_SERVER['SERVER_NAME'];       // localhost
echo $_SERVER['SERVER_PORT'];       // 80
echo $_SERVER['REMOTE_ADDR'];       // 127.0.0.1 (user's IP)
echo $_SERVER['HTTP_USER_AGENT'];   // User's browser info
echo $_SERVER['SCRIPT_NAME'];       // /myphp/page.php
echo $_SERVER['PHP_SELF'];          // /myphp/page.php

// Detect HTTPS
$isHttps = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on';

// Build the current full URL
$currentUrl = ($isHttps ? "https" : "http") . "://"
    . $_SERVER['HTTP_HOST']
    . $_SERVER['REQUEST_URI'];
echo $currentUrl;  // http://localhost/myphp/demo.php
?>
💡 Tip: $_SERVER['REMOTE_ADDR'] gives you the user's IP address (though it may be the proxy's IP if one sits in front). $_SERVER['HTTP_USER_AGENT'] lets you detect the browser type, but don't rely on it for anything critical — user agents are trivially spoofed.


3. $_GET — URL Query Parameters

Append ?key=value pairs to a URL and PHP automatically parses them into $_GET:

TEXT 📖 Display only
http://localhost/search.php?q=PHP&page=2&sort=newest
                              ↑          ↑       ↑
                         $_GET['q'] $_GET['page'] $_GET['sort']
PHP
<?php
// search.php
$keyword = $_GET['q'] ?? "No search term provided";
$page    = $_GET['page'] ?? 1;
$sort    = $_GET['sort'] ?? "relevance";

echo "Search term: {$keyword}<br>";
echo "Page {$page}<br>";
echo "Sort by: {$sort}<br>";
?>

Output:

TEXT 📖 Display only
<h3>Products — Page {25}</h3>
<a href='?page={value}' {value}>{value}</a> 
PHP
<?php
$page = (int)($_GET['page'] ?? 1);
$perPage = 20;

echo "<h3>Products — Page {$page}</h3>";

// Generate pagination links
for ($i = 1; $i <= 5; $i++) {
    $active = ($i == $page) ? "style='font-weight:bold;color:red'" : "";
    echo "<a href='?page={$i}' {$active}>{$i}</a> ";
}
?>

Output:

TEXT 📖 Display only
Output displayed
💡 Tip: Values in $_GET are always strings ("2", not 2). Cast them with (int) or intval() before using them in math.


4. $_POST — Form Data

$_POST receives data submitted by forms that use method="POST". This is the core interaction pattern of web development:

▶ Example: Handling a Form Submission

Output:

TEXT 📖 Display only
<h3>Message received!</h3>
<p><strong>{Alice}:</strong> {25}</p>
<p style='color:red'>Please fill in all fields</p>
PHP
<?php
// Check if this is a POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $message = trim($_POST['message'] ?? '');
    
    if ($name && $message) {
        echo "<h3>Message received!</h3>";
        echo "<p><strong>{$name}:</strong> {$message}</p>";
    } else {
        echo "<p style='color:red'>Please fill in all fields</p>";
    }
}
?>

<form method="POST" action="">
    <p>
        <label>Name:</label>
        <input type="text" name="name" value="<?= $_POST['name'] ?? '' ?>">
    </p>
    <p>
        <label>Message:</label>
        <textarea name="message"><?= $_POST['message'] ?? '' ?></textarea>
    </p>
    <button type="submit">Submit</button>
</form>

Output:

TEXT 📖 Display only
Output displayed
💡 Tip: action="" submits to the same page — a common pattern where one PHP file both displays the form and processes the submission.


5. GET vs POST

GET POST
Data location URL query string (visible) HTTP request body (hidden)
Data size ~2048 characters Theoretically unlimited
Bookmarkable / shareable ✅ Yes ❌ No
Browser caching Cached Not cached
Best for Search, pagination, filters Login, sign-up, data modification
Security Parameters exposed in URL Relatively safer (but not encrypted)
TEXT 📖 Display only
GET  →  "Show me page 2 of the catalog"    → Best for queries
POST →  "Here are my login credentials"     → Best for mutations
💡 Tip: Here's the golden rule — use GET for read operations, POST for write operations. Never, ever put passwords, credit card numbers, or any sensitive data into a GET query string — they'll end up in the browser history, server logs, and referrer headers.

PHP
<?php
// $_REQUEST merges $_GET + $_POST + $_COOKIE
// Don't use it! It's unsafe and you can't tell where the data came from
$unreliable = $_REQUEST['name'] ?? '';
// Always use explicit $_GET or $_POST
?>
▶ Try it Yourself

Output:

TEXT 📖 Display only
Output displayed

❓ FAQ

Q Can $_GET pass arrays?
A Yes. ?tags[]=PHP&tags[]=MySQL produces $_GET['tags'] = ['PHP', 'MySQL']. ?user[name]=John&user[age]=25 creates a nested array.
Q Where are POST parameters? They aren't in the URL.
A POST parameters travel in the HTTP request body. Open your browser's Developer Tools → Network tab to inspect them.
Q I've seen sites with both ?key=val in the URL AND a POST form. How?
A A common pattern is a form with action="page.php?id=1" — the id=1 comes through as GET while the form fields go through POST. A single request can carry both.

📖 Summary

📝 Exercises

  1. Create greet.php: accept a ?name=YourName URL parameter and display "Hello, YourName!". If no name is provided, show "Hello, Guest!".
  2. Build a pagination demo page: accept ?page=N, display "You are on page N", and generate links for pages 1 through 10.
  3. Build a guestbook form (using POST): submissions appear below the form. Store messages in a file (hint: file_put_contents + file_get_contents).
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏