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
📖 参照専用
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>";
?>
▶ サンプル: Pagination Links
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> ";
}
?>
💡 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:
▶ サンプル: Handling a Form Submission
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>
💡 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
📖 参照専用
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.
▶ サンプル: $_REQUEST (Not Recommended)
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
?>
❓ よくある質問
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.📖 まとめ
$_SERVERprovides server info — URL, IP, request method, and more$_GETcaptures URL query parameters (?key=val, used for search and pagination)$_POSTcaptures form submissions (method="POST", used for login and registration)- GET is for read operations (queries); POST is for write operations (mutations)
- Never use GET for passwords or other sensitive data
- Use
$_GET['key'] ?? 'default'for safe parameter access - Avoid
$_REQUEST— it muddles data sources together
📝 練習問題
- Create
greet.php: accept a?name=YourNameURL parameter and display "Hello, YourName!". If no name is provided, show "Hello, Guest!". - Build a pagination demo page: accept
?page=N, display "You are on page N", and generate links for pages 1 through 10. - Build a guestbook form (using POST): submissions appear below the form. Store messages in a file (hint:
file_put_contents+file_get_contents).