Forms and $_GET / $_POST
PHP receives form data submitted by a visitor through two superglobal arrays, $_GET and $_POST, depending on the HTML form's method attribute.
Reading Form Data
When an HTML form's method is GET, submitted values appear in the URL and land in $_GET. When it's POST, values are sent in the request body (not visible in the URL) and land in $_POST.
<form action="process.php" method="POST">
<input type="text" name="username">
<button type="submit">Submit</button>
</form>
<?php
// process.php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = htmlspecialchars($_POST['username'] ?? '');
echo "Hello, $username!";
}
?>
GET vs POST
GET is appropriate for non-sensitive data like search queries, where a bookmarkable, shareable URL is desirable. POST is the right choice for anything sensitive, like passwords, or for actions that change data, like submitting an order.
Common Mistakes
- Using GET for sensitive data like passwords, which ends up visible in the browser's URL and history.
- Trusting form input directly without validating or sanitising it before use.
- Forgetting the null coalescing operator or isset() check, causing a warning when an expected field is missing from the submission.
- Not escaping user-submitted output with htmlspecialchars() before echoing it back into HTML, opening the door to cross-site scripting (XSS).
Professional Tip
Always run user-submitted text through htmlspecialchars() before echoing it back into an HTML page. This converts special characters like < and > into safe HTML entities, closing off a major source of cross-site scripting vulnerabilities.
Your Turn
Build a simple feedback form using POST with fields for name and message, and a processing script that safely displays the submitted values back to the user.
Mini Quiz
Which superglobal array holds data from a form submitted with method="POST"?
$_POST superglobal array, keyed by each input's name attribute.