$_GET and $_POST

Collect data sent from HTML forms and URLs.

Syntax$name = $_GET['name'] ?? ''; $email = $_POST['email'] ?? '';

$_GET holds values passed in the URL query string, for example page.php?name=Ann. $_POST holds values from a form submitted with method="post".

Because these depend on a real browser request, the snippet below only illustrates how you would read them. Always validate and sanitize incoming data before using it.

Example

Example · php
// A typical form handler (illustrative, not run here)
<?php
$name = $_POST['name'] ?? 'Anonymous';
$email = $_POST['email'] ?? '';

if ($email !== '') {
    echo "Thanks, $name!";
} else {
    echo "Please enter an email.";
}

When to use it

  • Read search query parameters from $_GET['q'] to filter a product listing page.
  • Collect a login form's username and password from $_POST and pass them to an authentication function.
  • Detect the request method via $_SERVER['REQUEST_METHOD'] to route GET and POST to different handlers.

More examples

Reading $_GET parameters

$_GET holds URL parameters; htmlspecialchars() prevents XSS when echoing user input into HTML.

Example · php
<?php
// URL: /search?q=widget&page=2
$query = htmlspecialchars($_GET['q']    ?? '');
$page  = (int)             ($_GET['page'] ?? 1);

echo "Searching for '$query' on page $page";

Processing a POST form

Checking REQUEST_METHOD ensures the handler only runs on POST; filter_input() validates and sanitises in one call.

Example · php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email    = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
    $password = $_POST['password'] ?? '';

    if ($email && strlen($password) >= 8) {
        echo "Credentials valid for $email";
    } else {
        echo 'Invalid input';
    }
}

Redirecting after POST

Redirecting after a successful POST prevents the browser from resubmitting the form when the user refreshes.

Example · php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Process the form...
    $id = 42; // new record ID

    header('Location: /orders/' . $id);
    exit; // always exit after header redirect
}

Discussion

  • Be the first to comment on this lesson.