$_GET — Reading the Query String
A visitor searches Pageturn for "dune" and lands on /search.php?q=dune&page=2. Everything after the ? is the query string, and it is how a link or a search box tells your script what the visitor wants. PHP unpacks it into an array called $_GET before your first line runs.
The rule
$_GET holds the URL's query string: always text, always untrusted.
<?php
// /search.php?q=dune&page=2
$q = $_GET['q'] ?? ''; // "dune"
$page = (int) ($_GET['page'] ?? 1); // 2
echo "Results for " . htmlspecialchars($q);What to know about $_GET:
- It is an associative array. Each
name=valuepair in the query string becomes a key and a value. It is a superglobal, so it is visible everywhere, even inside functions. - Values are strings.
page=2arrives as"2", not the integer 2. Cast or validate before doing arithmetic. (A name with brackets, as intag[]=scifi&tag[]=classic, arrives as an array.) - Keys may be missing. The visitor controls the URL, so any key may be absent. Read with
??to avoid warnings. - It is untrusted. Anyone can type
?q=<script>...into the address bar. Escape withhtmlspecialchars()before printing, or you open the door to cross-site scripting.
When to use GET. The query string is visible in the address bar, saved in browser history and server logs, and can be bookmarked or shared. That makes GET right for requests that only read: searching, filtering, sorting, pagination. It is wrong for anything that changes data, such as placing an order, and for anything secret, such as a password.
A search form sends GET when you write <form method="get" action="search.php"> with an <input name="q">; the input's name becomes the key.
The shortcut
Every time you touch a $_GET value, run the three checks: exists? right type? safe to print?
Exists?
The first visit has no
page. Read it with a fallback:$_GET['page'] ?? 1.
Drills
Answer fast — trust the rule.
For /search.php?page=2, what is $_GET['page']?
Which is the safest way to read an optional sort parameter?
Which action is a good fit for a GET request?
Why pass the search text through htmlspecialchars() before echoing it?
Remember
- $_GET holds the URL's query string: always text, always untrusted.
- Shortcut: exists? right type? safe to print?
- Trap: never use GET for actions that change data or for secrets; the URL is public.
