What are some common methods for preserving form state in PHP applications?

Preserving form state in PHP applications is important to ensure that user input is not lost when a form is submitted. Common methods for preserving form state include using sessions, hidden form fields, and cookies to store and retrieve form data.

// Using sessions to preserve form state
session_start();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $_SESSION['form_data'] = $_POST;
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Retrieve form data from session
$form_data = isset($_SESSION['form_data']) ? $_SESSION['form_data'] : [];
```

```php
// Using hidden form fields to preserve form state
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Process form data
} else {
    // Populate form fields with previous data
    $name = isset($_POST['name']) ? $_POST['name'] : '';
    $email = isset($_POST['email']) ? $_POST['email'] : '';
}

// HTML form with hidden fields
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="text" name="name" value="<?php echo $name; ?>">
    <input type="email" name="email" value="<?php echo $email; ?>">
    <input type="hidden" name="form_submitted" value="1">
</form>
```

```php
// Using cookies to preserve form state
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    setcookie('name', $_POST['name'], time() + 3600);
    setcookie('email', $_POST['email'], time() + 3600);
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Retrieve form data from cookies
$name = isset($_COOKIE['name']) ? $_COOKIE['name'] : '';
$email = isset($_COOKIE['email']) ? $_COOKIE['email'] : '';