Sticky Forms
What Is a Sticky Form? In simple terms: A sticky form "remembers" what the user typed. When a submission fails validation and the form is shown again, every field still contains the user's input, so t
What Is a Sticky Form?
In simple terms: A sticky form "remembers" what the user typed. When a submission fails validation and the form is shown again, every field still contains the user's input, so they only need to correct the fields with errors.
Technically: A sticky form re-renders its fields using the previously submitted values: text inputs get a value attribute, textareas get content, and choices get checked or selected. The values must be escaped when they are printed back into the HTML.
Why It Matters
Imagine filling in ten fields, mistyping your email address, and being returned to an empty form. Many users give up at that point. Sticky forms are a basic usability requirement for every form with validation.
How Each Field Type Becomes Sticky
| Field | How to Restore the Value |
|---|---|
| Text, email, number, date, … | value="<?= e($old['field']) ?>" |
| Textarea | Content between the tags: <textarea><?= e($old['field']) ?></textarea> |
| Select | Add selected to the matching <option> |
| Radio button | Add checked to the matching button |
| Checkbox / checkbox group | Add checked to each submitted value |
| Password | Do not refill — make the user type it again |
| File | Cannot be refilled — browsers do not allow setting a file input's value |
A Helper for Old Values
<?php
function e(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
function old(array $old, string $key, string $default = ''): string
{
$value = $old[$key] ?? $default;
return is_string($value) ? $value : $default;
}
old()returns the previously submitted value for a field, or a default (for example, a value from the database when editing a record).- It returns only strings; unexpected arrays (from manipulated requests) fall back to the default.
e()escapes the value for HTML. Always combine them:e(old($old, 'name')).
Example: Re-Rendering After a Failed Submission
Suppose a user submitted this data, and the email was rejected:
<?php
function e(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
function old(array $old, string $key, string $default = ''): string
{
$value = $old[$key] ?? $default;
return is_string($value) ? $value : $default;
}
$old = [
'name' => 'Asha "AK" Kumar',
'email' => 'asha@',
'message' => "Hi <team>,\nPlease call me.",
'topic' => 'billing',
'contact' => ['email', 'phone'],
];
$errors = ['email' => 'Please enter a valid email address.'];
$topics = ['general' => 'General question', 'billing' => 'Billing', 'support' => 'Technical support'];
$contactMethods = ['email' => 'Email', 'phone' => 'Phone', 'whatsapp' => 'WhatsApp'];
$selectedContact = is_array($old['contact'] ?? null) ? $old['contact'] : [];
printf("<input name=\"name\" value=\"%s\">\n", e(old($old, 'name')));
printf("<input name=\"email\" value=\"%s\"%s>\n",
e(old($old, 'email')),
isset($errors['email']) ? ' aria-invalid="true"' : '');
if (isset($errors['email'])) {
printf("<p class=\"error\">%s</p>\n", e($errors['email']));
}
printf("<textarea name=\"message\">%s</textarea>\n", e(old($old, 'message')));
echo "<select name=\"topic\">\n";
foreach ($topics as $value => $label) {
printf(" <option value=\"%s\"%s>%s</option>\n",
e($value), old($old, 'topic') === $value ? ' selected' : '', e($label));
}
echo "</select>\n";
foreach ($contactMethods as $value => $label) {
printf("<label><input type=\"checkbox\" name=\"contact[]\" value=\"%s\"%s> %s</label>\n",
e($value), in_array($value, $selectedContact, true) ? ' checked' : '', e($label));
}
Output (HTML)
<input name="name" value="Asha "AK" Kumar">
<input name="email" value="asha@" aria-invalid="true">
<p class="error">Please enter a valid email address.</p>
<textarea name="message">Hi <team>,
Please call me.</textarea>
<select name="topic">
<option value="general">General question</option>
<option value="billing" selected>Billing</option>
<option value="support">Technical support</option>
</select>
<label><input type="checkbox" name="contact[]" value="email" checked> Email</label>
<label><input type="checkbox" name="contact[]" value="phone" checked> Phone</label>
<label><input type="checkbox" name="contact[]" value="whatsapp"> WhatsApp</label>
Why Escaping Is Essential Here
- The name contains double quotes. Without escaping,
value="Asha "AK" Kumar"would end the attribute afterAsha— the rest of the name would be lost and could even inject new attributes. - The message contains
<team>, which the browser would otherwise interpret as an HTML tag. - Sticky forms print user input back into the page, which is exactly where XSS happens. A malicious user could also trick another person into submitting a crafted form, so even "the user's own data" must be escaped.
Where the Values Come From
| Situation | Source of $old |
|---|---|
| Same request after a failed POST | $_POST (or the cleaned values from your validation function) |
| After a redirect (PRG pattern) | Values saved in the session ("flashed") before the redirect |
| Editing an existing record | Database values as defaults, overridden by submitted values after an error |
Sticky Forms With Post/Redirect/Get
Redirecting after errors (not only after success) keeps the browser's back and refresh buttons safe in every case. The submitted values and errors are stored in the session for exactly one request:
<?php
// contact.php
session_start();
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
$input = [
'name' => is_string($_POST['name'] ?? null) ? trim($_POST['name']) : '',
'email' => is_string($_POST['email'] ?? null) ? trim($_POST['email']) : '',
];
$errors = [];
if ($input['name'] === '') {
$errors['name'] = 'Please enter your name.';
}
if (filter_var($input['email'], FILTER_VALIDATE_EMAIL) === false) {
$errors['email'] = 'Please enter a valid email address.';
}
if ($errors !== []) {
$_SESSION['_old'] = $input; // flash the input
$_SESSION['_errors'] = $errors; // flash the errors
header('Location: /contact.php', true, 303);
exit;
}
// ... process the valid data ...
$_SESSION['_success'] = 'Thanks! We will get back to you soon.';
header('Location: /contact.php', true, 303);
exit;
}
// GET: read the flashed values once, then remove them
$old = $_SESSION['_old'] ?? [];
$errors = $_SESSION['_errors'] ?? [];
$success = $_SESSION['_success'] ?? null;
unset($_SESSION['_old'], $_SESSION['_errors'], $_SESSION['_success']);
?>
<!-- render the form with old() and $errors as shown above -->
How It Works
- Every POST ends with a redirect, whether it succeeded or failed.
- On failure, input and errors are stored in the session before redirecting.
- The following GET request reads them once and removes them, so a later refresh shows a clean form.
- Frameworks provide this as a feature: Laravel's
old('field')helper and its validation redirects work exactly this way.
Never flash passwords or other secrets into the session for re-display. Exclude them from
$_SESSION['_old'].
Sticky Values When Editing Records
When editing existing data, the form shows database values at first and submitted values after a validation error:
<?php
function old(array $old, string $key, string $default = ''): string
{
$value = $old[$key] ?? $default;
return is_string($value) ? $value : $default;
}
$product = ['name' => 'Desk Lamp', 'price' => '1299']; // from the database
$old = ['name' => 'Desk Lamp LED', 'price' => '-5']; // submitted, failed validation
echo old([], 'name', $product['name']) . "\n"; // first visit: no submitted values
echo old($old, 'name', $product['name']) . "\n"; // after an error: user's edit wins
echo old($old, 'price', $product['price']) . "\n";
Output
Desk Lamp
Desk Lamp LED
-5
The default argument provides the stored value, and submitted values take priority. Showing the invalid price -5 (together with an error message) is correct: the user sees what they entered and why it was rejected.
Common Mistakes
Refilling Without Escaping
Effect: Broken attributes and XSS vulnerabilities.
Fix: Always e(old(...)).
Refilling Passwords
Effect: Passwords appear in the HTML source and may be stored in the browser or session.
Fix: Leave password fields empty after errors.
Forgetting Choices and Textareas
Effect: Text fields stay filled, but selections are lost.
Fix: Restore selected/checked and textarea content too.
Loose Comparisons for Selected Options
Effect: Wrong options appear selected.
Fix: Compare with === and in_array(..., true).
Keeping Old Input Forever
Effect: Stale values reappear on later visits.
Fix: Remove flashed values from the session immediately after reading them.
Best Practices
- Refill every field type except passwords and files.
- Escape every refilled value for its context.
- Use a helper such as
old()with defaults for edit forms. - Combine sticky forms with Post/Redirect/Get by flashing input and errors to the session.
- Show the error message next to the field that caused it, together with the user's value.
Official reference: https://www.php.net/manual/en/tutorial.forms.php