devnotes.

Handling Form Data with GET and POST

PHP's superglobals are built-in arrays available in every scope, without needing global. The two most common for forms are $_GET and $_POST.

<form action="submit.php" method="post">
    <input type="text" name="username">
    <input type="email" name="email">
    <button type="submit">Submit</button>
</form>
// submit.php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');

    if ($username === '' || $email === '') {
        die('All fields are required.');
    }
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        die('Invalid email address.');
    }

    // proceed with validated, sanitized data
}

GET vs POST: GET data appears in the URL (?search=php), is bookmarkable, cacheable, and has size limits — appropriate for search forms and filters. POST data is sent in the request body, not shown in the URL, and is the right choice for anything that changes data (logins, form submissions, payments).

Always use $_POST['field'] ?? '' (or filter_input()) rather than accessing array keys directly, to avoid warnings and undefined-index errors when a field is missing.

PHP Form Handling with GET and POST | DevNotes