Explain it simply
Explain it simply
When a browser sends a request, it names a method that says what it wants to do. GET means "give me this page" and asking again should change nothing. POST means "take this data and act on it", and it is used for actions that change something, such as placing an order or creating an account.
PHP puts the query string of a GET URL, such as ?keyword=php, into $_GET, and the form data in a POST body into $_POST. Users choose the values in both, so you validate them first and escape them before they go into HTML.
Problem → Why → Solution
The problem: a search term breaks the page and a robot clicks the delete link
Most people writing their first search page echo $_GET["keyword"] directly. If the URL is ?keyword=<script>alert(1)</script>, that script lands straight in the HTML and runs in the visitor's browser: this is XSS. The second problem is a delete.php?id=5 link that deletes on GET. A browser prefetch, a search-engine crawler or an extension that merely opens the link is enough to destroy data.
<?php
// search.php?keyword=<script>alert(1)</script>
echo "You searched for: " . $_GET["keyword"]; // 1. raw input printed into HTML
// delete.php?id=5 (reached by an ordinary link, a crawler or a prefetch)
deleteProduct((int) $_GET["id"]); // 2. a GET request changes dataWhy does this happen?
Caches, prefetchers and crawlers are designed to open GET URLs on the assumption that nothing changes, so deleting on GET breaks the basic rule of the protocol. Echoing raw input is dangerous because the browser cannot tell the user's text from your own HTML. The cure is to move state-changing actions to POST (with a CSRF token) and to escape every output with htmlspecialchars().
Core concept: the method states intent and decides where data travels
The HTTP method states the browser's intent. GET should be safe (it changes nothing) and idempotent (repeating it gives the same result), while POST asks for something new to be done, so repeating it does it again. PHP puts the URL's query string into $_GET and a form body into $_POST; $_GET is filled even on a POST request if the URL carries a query.
| Aspect | GET | POST |
|---|---|---|
| Intended use | read, search, filter | create, update, delete, log in |
| Where data travels | the URL's query string | the request body |
| Repeating it | same result, nothing changes | may change state again |
| Bookmark or share | yes, the URL holds the state | no, the URL carries no data |
| Caching | browsers and proxies may cache | not cached by default |
| History and logs | the URL appears in history, logs and Referer | the body is not in the URL (still needs HTTPS) |
| Size | limited by URL length limits | limited by post_max_size and server limits |
So use GET for things people want to share or bookmark, such as search, filters, sorting and pagination, and POST for logins, orders, deletions and anything secret. Never put a password or token in a URL: it ends up in browser history, server access logs and the Referer header sent to other sites. A POST body is not encrypted either, so without HTTPS it can still be read.
When you read values, do three separate jobs. First, handle absence with ?? and a default. Second, check the type and shape (is_string(), filter_var(), an allowlist). Third, when you print, escape with htmlspecialchars($s, ENT_QUOTES, 'UTF-8'). Validation decides whether to accept a value, and escaping makes it safe for one output context (HTML), so neither replaces the other. Remember too that the method alone provides neither authorization (who is allowed to do this) nor CSRF protection.
- Browser sends method, URL and body
- PHP splits: query to $_GET, body to $_POST
- Check each field's presence and type
- Escape whenever you print it back
Validation and escaping are two different jobs; skipping either one leaves a bug or a security hole.
General pattern
$text = $_GET["key"] ?? ""; // from the URL query string
$text = $_POST["key"] ?? ""; // from the request body
$n = filter_var($raw, FILTER_VALIDATE_INT, [
"options" => ["default" => 1, "min_range" => 1],
]);
echo htmlspecialchars($text, ENT_QUOTES, "UTF-8");
if ($_SERVER["REQUEST_METHOD"] === "POST") { /* change state here */ }?? supplies a default for a missing key. filter_var() returns the value when it is valid and false (or the default option) when it is not. Use htmlspecialchars() at the point of output, not when storing the data.
Example: a GET-driven search page
The CLI has no web request, so this example writes the search page as a function, renderSearch(array $get), and calls it with fixed arrays. renderSearch(["keyword" => "php"]) is what a browser opening search.php?keyword=php would trigger. In a real page you would simply call renderSearch($_GET).
<?php
function textParam(array $source, string $key): string
{
$value = $source[$key] ?? "";
return is_string($value) ? trim($value) : "";
}
function renderSearch(array $get): string
{
$keyword = textParam($get, "keyword");
if ($keyword === "") {
return "Please type a search keyword.";
}
$options = ["options" => ["default" => 1, "min_range" => 1, "max_range" => 50]];
$page = filter_var(textParam($get, "page"), FILTER_VALIDATE_INT, $options);
return "You searched for: " . htmlspecialchars($keyword, ENT_QUOTES, "UTF-8")
. " (page $page)";
}
echo renderSearch(["keyword" => "php"]), "\n";
echo renderSearch(["keyword" => "php", "page" => "3"]), "\n";
echo renderSearch(["keyword" => "php", "page" => "abc"]), "\n";
echo renderSearch(["keyword" => "<script>alert(1)</script>"]), "\n";
echo renderSearch([]), "\n";Code breakdown
- Read one text field
return is_string($value) ? trim($value) : "";If the value is not a string (an array from ?keyword[]=a), it returns an empty string; otherwise it trims the spaces. One helper solves the array-instead-of-string problem in a single place.
- Missing keyword
return "Please type a search keyword.";A missing, empty or all-spaces keyword all end up here, and the rest of the function does not run.
- Validate the page
$page = filter_var(textParam($get, "page"), FILTER_VALIDATE_INT, $options);"3" becomes the int 3, while "abc" or an empty value fails and yields the default of 1. So $page is always an int between 1 and 50.
- Escape on output
htmlspecialchars($keyword, ENT_QUOTES, "UTF-8")The angle brackets of <script> are replaced by their HTML entity codes, so the browser shows the text and never runs it (see the fourth line of the example output). Writing the flags explicitly avoids depending on a default that differs between PHP versions.
You searched for: php (page 1)
You searched for: php (page 3)
You searched for: php (page 1)
You searched for: <script>alert(1)</script> (page 1)
Please type a search keyword.Repeating a GET versus repeating a POST
To see idempotence with your own eyes, the script below uses an array in place of a database. handle() looks at the method: POST adds an item, GET only reads the list. The cart array is passed by reference (&) so the function can change it directly. Watch how calling GET twice gives the same result, while calling POST twice leaves two items.
<?php
$cart = []; // pretend this array is a database table
function handle(string $method, array $get, array $post, array &$cart): string
{
if ($method === "POST") {
$item = $post["item"] ?? "";
if (!is_string($item) || trim($item) === "") {
return "400 item is required";
}
$cart[] = trim($item);
return "201 added " . trim($item);
}
return "200 cart: " . ($cart === [] ? "(empty)" : implode(", ", $cart));
}
echo handle("GET", [], [], $cart), "\n";
echo handle("POST", [], ["item" => "pen"], $cart), "\n";
echo handle("POST", [], ["item" => "pen"], $cart), "\n";
echo handle("GET", [], [], $cart), "\n";
echo handle("GET", [], [], $cart), "\n";
echo handle("POST", [], ["item" => " "], $cart), "\n";The output is 200 cart: (empty), 201 added pen, 201 added pen, 200 cart: pen, pen, 200 cart: pen, pen, and 400 item is required. Notice that a user who clicks submit twice ends up with two pens, which is why the next lesson adds a redirect after POST (the PRG pattern) so a refresh does not resubmit.
filter_var, filter_input and JSON bodies
filter_var($value, FILTER_VALIDATE_INT) returns the int when the value is valid and false when it is not: "12abc" gives false, while " 12 " has its surrounding spaces trimmed and gives 12. filter_input(INPUT_GET, "page", ...) reads only the original request data PHP received, so in the CLI it returns NULL even if you assigned $_GET yourself (under a web server it works). That is why this lesson uses filter_var with arrays: it can be tried anywhere.
<?php
$_GET = ["page" => "3"];
var_dump(filter_input(INPUT_GET, "page", FILTER_VALIDATE_INT)); // CLI: no request
var_dump(filter_var($_GET["page"], FILTER_VALIDATE_INT));
var_dump(filter_var("12abc", FILTER_VALIDATE_INT));
var_dump(filter_var(" 12 ", FILTER_VALIDATE_INT));
var_dump(filter_var("aye@example.com", FILTER_VALIDATE_EMAIL));
var_dump(filter_var("aye@example", FILTER_VALIDATE_EMAIL));
var_dump(filter_var("maybe", FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE));The output is NULL, int(3), bool(false), int(12), string(15) "aye@example.com", bool(false) and NULL. With FILTER_NULL_ON_FAILURE the boolean filter returns NULL for invalid input instead of false, so "the user wrote false" and "the input is invalid" can be told apart. Compare the result with === false and never test it with if ($result): the int 0 is valid but falsy.
A JSON body does not end up in $_POST. PHP fills $_POST only for the application/x-www-form-urlencoded and multipart/form-data content types. JSON sent with fetch() must be read as a raw body with file_get_contents("php://input") and decoded with json_decode(). In the CLI php://input is empty, so the sample below supplies the JSON text itself.
<?php
echo "php://input in the CLI: [", file_get_contents("php://input"), "]\n";
echo "POST entries: ", count($_POST), "\n";
function readJsonBody(string $raw): string
{
try {
$data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
return "400 invalid JSON: " . $e->getMessage();
}
if (!is_array($data) || !isset($data["name"]) || !is_string($data["name"])) {
return "422 name is required";
}
return "200 hello " . htmlspecialchars($data["name"], ENT_QUOTES, "UTF-8");
}
echo readJsonBody('{"name":"Aye"}'), "\n";
echo readJsonBody('{"name":'), "\n";
echo readJsonBody('{"age":31}'), "\n";The output is php://input as [], POST entries 0, then 200 hello Aye, 400 invalid JSON: Syntax error and 422 name is required. JSON_THROW_ON_ERROR throws a JsonException for broken JSON instead of hiding it as null, so you can answer 400 and 422 separately.
In real projects
Where this shows up in real projects
On real sites, search boxes, category filters, sort dropdowns and pagination links are GET, because the URL can be shared, bookmarked and refreshed, and CDN and browser caches can help. Logins, checkouts and posting comments are POST. APIs behind JavaScript frontends use POST, PUT, PATCH and DELETE with JSON bodies, which PHP reads from php://input. When you build links, encode the query string with http_build_query() instead of concatenating it by hand, then escape the whole URL with htmlspecialchars() for the HTML attribute.
<?php
$params = ["q" => "php & tips", "page" => 2];
$url = "/search.php?" . http_build_query($params);
echo $url, "\n";
echo '<a href="' . htmlspecialchars($url, ENT_QUOTES, "UTF-8") . '">next</a>', "\n";/search.php?q=php+%26+tips&page=2
<a href="/search.php?q=php+%26+tips&page=2">next</a>The first line is the URL and the second is that URL placed in an HTML attribute. Encoding the & inside a query value as %26 and escaping the & that separates parameters for HTML (look at the second line) are two different layers doing two different jobs. In production, pair POST with CSRF tokens and HTTPS, and check who is allowed to act yourself instead of relying on the method.
Common mistakes
Common mistakes
1. Echoing user input without escaping it
With echo "You searched for: " . $_GET["keyword"];, the URL ?keyword=<script>alert(1)</script> makes the script run in the browser. Pass every value that goes into HTML through htmlspecialchars($value, ENT_QUOTES, 'UTF-8'). Even inside an attribute, ENT_QUOTES escapes the quotes.
2. Changing data on a GET request
A delete.php?id=5 link can be opened by a prefetch, a crawler or a link checker and delete the record just by being visited. Move state-changing actions into a POST form (with a CSRF token) and check REQUEST_METHOD === "POST" on the server.
3. Sending a password or token with GET
A password field in <form method="get"> produces a URL like login.php?password=..., which is left in browser history, bookmarks, server access logs and the Referer header. Send secrets only in a POST body over HTTPS.
4. Looking for a JSON payload in $_POST
When fetch() sends Content-Type: application/json, $_POST is an empty array. Without knowing that, people conclude "the data never arrived" and hunt for hours. Read the raw body with file_get_contents("php://input") and run json_decode() on it.
Best practices
Best practices
- Use GET for reading and searching only, and POST (with a CSRF token) for everything that changes state.
- Check is_string() on every text field, bound numbers with filter_var() including the range, and pick sort columns from an allowlist.
- Use htmlspecialchars($s, ENT_QUOTES, 'UTF-8') with explicit flags on every output, and build links with http_build_query().
- Compare filter_var results with === false, expect filter_input to work only on the web, and use filter_var for tests run in the CLI.
Mini challenge
Mini challenge: a GET listing and a POST subscription
Write a handleRequest() function that deals with each method. GET validates sort and page and returns a listing line, POST validates an email and subscribes it, and any other method returns 405.
- handleRequest(string $method, array $get, array $post): string
- GET: sort must be "name" or "price" (allowlist), otherwise "name"; validate page with filter_var between 1 and 100, defaulting to 1 → "200 listing page N sorted by S"
- POST: trim the email and validate it with FILTER_VALIDATE_EMAIL → "201 subscribed ..." (escaped with htmlspecialchars) or "422 invalid email"
- Return "405 method not allowed" for any other method, and print five test cases
<?php
function handleRequest(string $method, array $get, array $post): string
{
if ($method === "GET") {
// TODO: sort from an allowlist, page with filter_var and a default
}
if ($method === "POST") {
// TODO: trim the email, validate it, escape it for output
}
// TODO: every other method
return "";
}
// TODO: GET with good values, GET with bad values, POST valid, POST invalid, DELETEExpected: Expected output: 200 listing page 2 sorted by price 200 listing page 1 sorted by name 201 subscribed aye@example.com 422 invalid email 405 method not allowed
Show hint
Check the allowlist with in_array($sort, ["name", "price"], true), where the third argument true makes the comparison strict. Put default, min_range and max_range into the filter_var options. A value may arrive as an array, so test is_string() first.
Show solution
<?php
function handleRequest(string $method, array $get, array $post): string
{
if ($method === "GET") {
$sort = $get["sort"] ?? "";
if (!is_string($sort) || !in_array($sort, ["name", "price"], true)) {
$sort = "name";
}
$rawPage = $get["page"] ?? "";
$page = filter_var(is_string($rawPage) ? $rawPage : "", FILTER_VALIDATE_INT, [
"options" => ["default" => 1, "min_range" => 1, "max_range" => 100],
]);
return "200 listing page $page sorted by $sort";
}
if ($method === "POST") {
$email = $post["email"] ?? "";
$email = is_string($email) ? trim($email) : "";
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
return "422 invalid email";
}
return "201 subscribed " . htmlspecialchars($email, ENT_QUOTES, "UTF-8");
}
return "405 method not allowed";
}
echo handleRequest("GET", ["page" => "2", "sort" => "price"], []), "\n";
echo handleRequest("GET", ["page" => "-4", "sort" => "password"], []), "\n";
echo handleRequest("POST", [], ["email" => " aye@example.com "]), "\n";
echo handleRequest("POST", [], ["email" => "aye@example"]), "\n";
echo handleRequest("DELETE", [], []), "\n";Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- GET is for reading and searching (safe, idempotent, bookmarkable); POST is for actions that change state. Keep secrets out of URLs.
- Read $_GET and $_POST values with ??, then check them with is_string(), filter_var() (test with === false) and allowlists.
- Escape every output with htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); validation and escaping are two separate jobs.
- A JSON body does not reach $_POST: read php://input and json_decode() it. The method alone gives no authorization or CSRF protection.
PHP Security Manual — PHP Documentation Group