← Back to PHP Course | Chapter 2: Output & Input | Lesson 4 of 8

PHP $_GET & $_POST

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
<?php
$_GET['search'] = "php";
echo "Search query: " . $_GET['search'];
?>

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
<?php
$_POST['password'] = "secret123";
echo "Password never appears in the URL: " . strlen($_POST['password']) . " chars";
?>

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
<?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'];
?>

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
<?php
$_GET['id'] = "6"; // user could edit this in the address bar
$id = (int) $_GET['id'];
echo "Validated id: " . $id;
?>

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
<?php
$_SERVER['REQUEST_METHOD'] = 'POST';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    echo "Processing the submitted form.";
}
?>
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.