With method="get", the browser adds the form values to the end of the URL, after a question mark. This is called the query string.
<form action="search.php" method="get">
<label for="q">Search</label>
<input type="text" id="q" name="q">
<button type="submit">Go</button>
</form>
If the visitor types php arrays and submits, the browser requests:
search.php?q=php+arrays
PHP puts it in the $_GET array:
<?php
// URL: search.php?q=php+arrays
$query = trim($_GET["q"] ?? "");
echo "You searched for: " . htmlspecialchars($query);
You searched for: php arrays
Simulate it in the terminal
On the command line there is no URL, so we can fill $_GET ourselves to see what a page would do.
<?php
$_GET = ["q" => "php arrays", "page" => "2"];
$query = trim($_GET["q"] ?? "");
$page = (int) ($_GET["page"] ?? 1);
echo "Search: $query, page $page";
Search: php arrays, page 2
When GET is the right choice
Use GET when the request only reads or filters data and does not change anything:
- Search boxes
- Filters and sorting (
?category=books&sort=price) - Pagination (
?page=3) - Pages a person might bookmark or share
GET requests can be bookmarked, shared and cached, because everything is in the URL.
When not to use GET
- Passwords and secrets. The URL is saved in browser history, server logs and the Referer header.
- Actions that change data (delete, buy, send). A link or an image tag could trigger them by accident.
- Large data. URLs have length limits.
Links also use GET
A normal link is a GET request. That is why you can write query strings by hand in a link.
<?php
$page = 3;
$category = "books & games";
echo '<a href="list.php?' . http_build_query(["category" => $category, "page" => $page]) . '">Page 3</a>';
<a href="list.php?category=books+%26+games&page=3">Page 3</a>
http_build_query() encodes special characters for you, such as the &. Never build query strings by joining raw text.
Always read with a default
<?php
$page = (int) ($_GET["page"] ?? 1);
if ($page < 1) {
$page = 1;
}
A visitor can remove or change any part of the URL, so give every value a safe default.
GET data is visible
$_GET can be read by the visitor and by anyone looking over their shoulder. Never put private data there, and never trust it.