$_GET and $_POSThtmlspecialchars()get-example.php Search form using GET - see data in URL
post-example.php Contact form using POST - data hidden in request body
combined.php Self-submitting form with validation
| Feature | GET | POST |
|---|---|---|
| Data location | URL query string | Request body |
| Visibility | Visible in URL, logs, history | Hidden (but not encrypted!) |
| Size limit | ~2KB (URL length limit) | Server-configurable (usually MB) |
| Bookmarkable | Yes | No |
| Cached | Yes | No |
| Use for | Search, filters, navigation | Login, signup, data changes |
<?php // GET data (from URL: ?name=Alice&age=25) $name = $_GET['name'] ?? ''; // 'Alice' $age = $_GET['age'] ?? ''; // '25' // POST data (from form submission) $email = $_POST['email'] ?? ''; $password = $_POST['password'] ?? ''; // The ?? operator provides a default if key doesn't exist // This prevents "undefined index" warnings ?>
<?php
// Common pattern: show form on GET, process on POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Form was submitted - process the data
$name = $_POST['name'] ?? '';
echo "Processing form for: " . htmlspecialchars($name);
} else {
// Show the form
echo '<form method="POST">...</form>';
}
?>
// WRONG - XSS vulnerability! echo "Hello, " . $_POST['name']; // RIGHT - escape HTML entities echo "Hello, " . htmlspecialchars($_POST['name'], ENT_QUOTES, 'UTF-8');
If a user enters <script>alert('hacked')</script> as their name, the wrong version executes that JavaScript. The right version displays it as harmless text.
<form method="POST" action="process.php">
<!-- Text input -->
<input type="text" name="username">
<!-- Email (browser validates format) -->
<input type="email" name="email">
<!-- Password (hidden characters) -->
<input type="password" name="password">
<!-- Dropdown -->
<select name="country">
<option value="us">United States</option>
<option value="uk">United Kingdom</option>
</select>
<!-- Submit button -->
<button type="submit">Submit</button>
</form>
The name attribute is crucial! It becomes the key in $_GET or $_POST.
If you forget the name attribute, PHP won't receive that field's data.
isset($_POST['field'])!empty($_POST['field'])htmlspecialchars()← Previous: Hello World | Tutorial Home | Next: Headers & Metadata →