PHP $_GET & $_POST
In this page:
Understanding $_GET
$_GET collects values appended to the URL as a query string (?search=php), which means the data is visible in the address bar, browser history, and server logs. That visibility is a feature for shareable, bookmarkable pages like search results — and a liability for anything sensitive.
Example: Understanding $_GET
<?php
$_GET['search'] = "php";
echo "Search query: " . $_GET['search'];
?>
Login to try C/C++/Java/PHP code in the editor
Understanding $_POST
$_POST carries its data in the HTTP request body instead of the URL, so it never appears in the address bar or gets cached in browser history. That's why login forms, payment forms, and anything else handling sensitive data almost always use POST rather than GET.
Example: Understanding $_POST
<?php
$_POST['password'] = "secret123";
echo "Password never appears in the URL: " . strlen($_POST['password']) . " chars";
?>
Login to try C/C++/Java/PHP code in the editor
When to Use $_GET vs $_POST
As a rule of thumb: use $_GET for requests that only *read* data and are safe to bookmark or reload (search filters, pagination). Use $_POST for anything that *changes* server state — creating an account, placing an order — where an accidental page reload shouldn't silently repeat the action.
Example: When to Use $_GET vs $_POST
<?php
// $_GET for reading/searching -- safe to bookmark
$_GET['page'] = 2;
// $_POST for actions that change state
$_POST['create_account'] = true;
echo "GET page: " . $_GET['page'];
?>
Login to try C/C++/Java/PHP code in the editor
Safe $_GET Parameters
Because $_GET values live in the URL, a user can edit them directly in the address bar before the request even reaches your server — ?id=5 becomes ?id=6 with zero effort. Never assume a $_GET value is the one your own links generated; validate and sanitize it exactly as you would any other user input.
Example: Safe $_GET Parameters
<?php
$_GET['id'] = "6"; // user could edit this in the address bar
$id = (int) $_GET['id'];
echo "Validated id: " . $id;
?>
Login to try C/C++/Java/PHP code in the editor
Processing POST Forms
Before acting on a $_POST submission, confirm $_SERVER[REQUEST_METHOD] === POST (or check that the expected keys are actually set). Skipping this check means a script written to expect a form submission can misbehave — or throw warnings — on a plain page load.
Example: Processing POST Forms
<?php
$_SERVER['REQUEST_METHOD'] = 'POST';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo "Processing the submitted form.";
}
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: