Sticky Forms

Ma Mahalakshmi V Updated 14 Nov 2026
6 min read ·Lesson 118 of 256

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

FieldHow to Restore the Value
Text, email, number, date, …value="<?= e($old['field']) ?>"
TextareaContent between the tags: <textarea><?= e($old['field']) ?></textarea>
SelectAdd selected to the matching <option>
Radio buttonAdd checked to the matching button
Checkbox / checkbox groupAdd checked to each submitted value
PasswordDo not refill — make the user type it again
FileCannot 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 after Asha — 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

SituationSource 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 recordDatabase 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

  1. Every POST ends with a redirect, whether it succeeded or failed.
  2. On failure, input and errors are stored in the session before redirecting.
  3. The following GET request reads them once and removes them, so a later refresh shows a clean form.
  4. 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

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Tutorial Index PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

Ask questions about Sticky Forms and get answers drawn from it.

Signed-in readers only.