Forms: GET, POST and superglobals
PHP was born to process web forms, and it is still one of its main jobs. When the user submits a form, the browser sends an HTTP request to the server with the typed data, and PHP makes it available in special arrays called superglobals. From this week on the code no longer runs only in the terminal: you will need PHP's built-in server. Start it with php -S localhost:8000 from the project folder and open http://localhost:8000 in the browser.
GET versus POST
A form uses the GET or POST method. With GET the data travels in the URL (?q=php&page=2): it is suited to searches and filters, because they can be bookmarked and shared, and it arrives in $_GET. With POST the data travels in the request body and arrives in $_POST: it is used for actions that change something, such as signing up, buying or publishing. Never send passwords by GET, because they would stay in the history and the server logs. The practical rule: GET to read, POST to modify.
<?php
// File: search.php (run: php -S localhost:8000)
declare(strict_types=1);
$query = $_GET['q'] ?? '';
$query = is_string($query) ? trim($query) : '';
?>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><title>Search</title></head>
<body>
<form method="get" action="search.php">
<label for="q">Search</label>
<input type="text" id="q" name="q" value="<?= htmlspecialchars($query, ENT_QUOTES, 'UTF-8') ?>">
<button type="submit">Go</button>
</form>
<?php if ($query !== ''): ?>
<p>You searched for: <strong><?= htmlspecialchars($query, ENT_QUOTES, 'UTF-8') ?></strong></p>
<?php endif; ?>
</body>
</html>Handling a POST and redirecting
The usual pattern for POST is: check the method with $_SERVER['REQUEST_METHOD'], read and validate the data, perform the action and redirect with header('Location: ...') followed by exit. Redirecting avoids a classic problem: if you answer directly with a page after a POST and the user presses F5, the browser asks whether to resubmit the form and may duplicate the action. This pattern is called Post/Redirect/Get. Before any header() no output may have been sent, not even a space.
<?php
// File: contact.php
declare(strict_types=1);
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = trim((string) ($_POST['name'] ?? ''));
$text = trim((string) ($_POST['text'] ?? ''));
if ($name !== '' && $text !== '') {
// Here you would save or send the message
header('Location: contact.php?sent=1');
exit;
}
$message = 'Please fill in all fields.';
}
$sent = ($_GET['sent'] ?? '') === '1';
?>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><title>Contact</title></head>
<body>
<?php if ($sent): ?><p>Thanks, message sent.</p><?php endif; ?>
<?php if ($message !== ''): ?>
<p><?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?></p>
<?php endif; ?>
<form method="post">
<input name="name" placeholder="Name">
<textarea name="text" placeholder="Message"></textarea>
<button type="submit">Send</button>
</form>
</body>
</html>Something fundamental: everything arriving in $_GET, $_POST or $_COOKIE is controlled by the user, and a malicious user can send anything, not just what your form allows. Never trust input data: it may be missing, have another type (an array instead of a string) or contain code. That is why we use ?? for missing values, (string) and trim to normalize, and in the next lesson we will validate with filter_var. Hidden fields and HTML maxlength limits protect nothing; they only improve convenience.
A practical detail about field names: the HTML name attribute is the key that will arrive in $_POST. If you write name="user_email", you will read $_POST['user_email']. Fields that are not sent, such as unchecked checkboxes, simply do not appear in the array, which is why ?? is always used when reading them.
Проверьте себя
Вопрос 1 из 1Which method would you use for a user signup form?
✎ Мои заметки
Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов