LEARN TO CODE | PHP | 02 PAGES AND FORMS

02.2 GET, POST and form processing

Trace browser form data into PHP, process the intended request method and return a readable response.

01 | A FORM CREATES A REQUEST

Continue using the PHP development server from 01.1. Create the files below inside one practice folder, preserving their filenames and subfolders. In VS Code open that folder, then start php -S 127.0.0.1:8000 in its terminal and open the named page through HTTP.

These are complete local examples for PHP 8. Text inputs and output are treated deliberately, but the examples are not a login system, a production deployment or a saved registration service. Where a page previews a submission only, nothing is sent or stored.

Typing into an input does not automatically change a PHP variable on the server. Submitting the form sends a request containing named values. PHP handles that request and builds a new response.

Think in two stages: the first GET displays a form; a later submission supplies data. A single .php file can handle both stages.

02 | THE FOUR CONNECTIONS

Trace the data path
Part Meaning
action="search.php" The URL receiving the submission
method="get" How the form supplies values
name="q" The submitted field key
$_GET['q'] PHP lookup for that submitted value

id connects an input to its label and helps browser-side code. name controls submission. An input with an id but no name does not supply that named form value.

Use a label with a matching for attribute. Leave clear spacing between its text and the input so the control is easy to read.

03 | GET FOR A SEARCH

A GET form puts ordinary submitted values in the URL query string, such as search.php?q=robot. That makes a search link convenient to copy or bookmark.

GET should retrieve information rather than perform an action such as deleting a record. Query values can appear in history and logs, so do not put passwords or secrets in a search-style URL.

Use this shared helper wherever the guide requests helpers.php. It escapes strings for HTML text and quoted ordinary HTML attribute values; it is not a universal encoder for every context.

helpers.php

<?php
function escapeHtml(string $text): string
{
    return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}

search.php

<?php
require_once __DIR__ . '/helpers.php';
$raw = $_GET['q'] ?? '';
$query = is_string($raw) ? trim($raw) : '';
$clubs = ['Robotics', 'Game Design', 'Art & Design'];
$matches = [];
if ($query !== '') {
    foreach ($clubs as $club) {
        if (stripos($club, $query) !== false) {
            $matches[] = $club;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Club search</title></head>
<body>
<h1>Club search</h1>
<form action="search.php" method="get">
    <label for="q">Search term : </label>
    <input id="q" name="q" value="<?= escapeHtml($query) ?>">
    <button type="submit">Search</button>
</form>
<?php if ($query !== ''): ?>
    <p>Results for <?= escapeHtml($query) ?>:</p>
    <ul>
        <?php foreach ($matches as $club): ?>
            <li><?= escapeHtml($club) ?></li>
        <?php endforeach; ?>
    </ul>
    <?php if (!$matches): ?><p>No matches.</p><?php endif; ?>
<?php endif; ?>
</body>
</html>

04 | READ THE SEARCH LINE BY LINE

$_GET is an associative array of parsed query values. The ?? operator supplies an empty string when q is absent, avoiding a missing-key warning on the initial request.

A request can submit an array instead of the string you expected. is_string checks the shape before trim or a string search function is used. This example treats an unexpected shape as an empty search.

stripos returns a position or false; checking !== false keeps a match at position 0. The query and displayed results are escaped when inserted into HTML.

05 | POST IN THE REQUEST BODY

A POST form sends ordinary fields in the request body rather than appending them to the address bar. PHP parses the usual HTML form encoding into $_POST.

POST does not encrypt data or authenticate a user. HTTPS provides transport protection; server validation and permission checks remain necessary. Changing the method alone does not make a request safe.

The following example only generates a greeting. It does not store, send or register anything, so it focuses on the request cycle before durable actions are introduced.

greeting.php

<?php
require_once __DIR__ . '/helpers.php';
$name = '';
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $raw = $_POST['name'] ?? '';
    if (!is_string($raw) || trim($raw) === '') {
        $message = 'Enter a name.';
    } else {
        $name = trim($raw);
        $message = 'Hello, ' . $name . '!';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Greeting form</title></head>
<body>
<h1>Greeting form</h1>
<form action="greeting.php" method="post">
    <label for="name">Name : </label>
    <input id="name" name="name" required value="<?= escapeHtml($name) ?>">
    <button type="submit">Greet me</button>
</form>
<?php if ($message !== ''): ?><p><?= escapeHtml($message) ?></p><?php endif; ?>
</body>
</html>

06 | ONE PAGE, TWO REQUEST STATES

On the initial GET, $message is empty, so the page displays only the form. On POST, the method check allows the submission-processing block to run.

The processor reads name, checks that it is a non-blank string, then creates a message. HTML at the bottom displays the message only when it exists.

Use $_POST for a POST field rather than mixing GET and POST automatically. Explicit data sources make the behaviour easier to understand and test.

07 | WHAT REACHES PHP?

Never assume browser presentation enforces trust
Control behaviour Submission consequence
A named text input Supplies its value, which can be empty
Disabled input Not normally submitted
Unchecked checkbox Normally absent
Select option Supplies the chosen option value
Hidden field Supplied data the client can still alter

Most ordinary form values arrive as strings, even when the input type is number. Validate and convert according to the task rather than assuming the browser sends an integer.

Browser required and type controls improve usability. A different client can bypass them, so PHP must still check the input.

08 | RETURN A FRIENDLY RESPONSE

If the input is missing, show what needs correcting rather than crashing. Preserve valid values in the form so the user does not have to retype everything.

When redisplaying data inside value="...", escape it for the quoted HTML attribute. An apostrophe or quotation mark is still user data, not permission to break the markup.

Here the form actions are fixed literal URLs. There is no need to print an unescaped request path into action.

09 | REFRESH AND REPEATED SUBMISSION

Refreshing a POST response may prompt the browser to resubmit it. For this greeting preview, that repeats a harmless response calculation.

For an action that saves state, a common pattern is POST → validate and perform the action → redirect with 303 → GET the result page. The redirect reduces accidental resubmission on refresh; it does not replace CSRF protection or database rules.

We will use that pattern for the session favourite in 02.4.

10 | PRACTISE BOTH METHODS

TRY IT YOURSELF

Use search.php to search for robot, an empty value and an unknown term. Then submit a name containing an apostrophe to greeting.php. Explain where the submitted data travels in each case.

Reveal guidance

robot finds Robotics; an empty query shows no results section; an unknown term gives No matches. The greeting should display the apostrophe normally. GET puts q in the URL; POST supplies name in the body. Neither method makes the value trusted.

Next, we will validate several fields together and keep accepted data separate from HTML output formatting.

KEEP LEARNING

Previous page 02.3 Validating input and escaping output

Official references: Includes and control structures · POST values · HTML escaping · Sessions · Cookies