How can PHP be used to retain form data when navigating back on a website?

When navigating back on a website, form data is typically lost because it is not stored anywhere. To retain form data, you can use PHP to store the form values in session variables when the form is submitted. Then, when the user navigates back to the form page, you can populate the form fields with the values stored in the session variables.

<?php
session_start();

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $_SESSION['name'] = $_POST['name'];
    $_SESSION['email'] = $_POST['email'];
    // Add more fields as needed
}

// Populate form fields with session data
$name = isset($_SESSION['name']) ? $_SESSION['name'] : '';
$email = isset($_SESSION['email']) ? $_SESSION['email'] : '';
// Add more fields as needed
?>

<form method="post" action="">
    <input type="text" name="name" value="<?php echo $name; ?>" placeholder="Name">
    <input type="email" name="email" value="<?php echo $email; ?>" placeholder="Email">
    <!-- Add more fields as needed -->
    <button type="submit">Submit</button>
</form>