How can a "Back" button be implemented in a PHP form using SESSION variables?

When navigating through a multi-step form in PHP, using SESSION variables to store form data, it can be useful to implement a "Back" button to allow users to go back to the previous step without losing their input. This can be achieved by storing the form data in SESSION variables on each step and then using these variables to repopulate the form fields when the user goes back.

<?php
session_start();

// Check if form data has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Store form data in SESSION variables
    $_SESSION['step1_data'] = $_POST['step1_field'];
    $_SESSION['step2_data'] = $_POST['step2_field'];
    // Redirect to the next step or process the form data
    header("Location: next_step.php");
    exit();
}

// Check if user clicked the "Back" button
if (isset($_POST['back_button'])) {
    // Redirect back to the previous step
    header("Location: previous_step.php");
    exit();
}

// Display the form with SESSION data
?>
<form method="post" action="">
    <input type="text" name="step1_field" value="<?php echo isset($_SESSION['step1_data']) ? $_SESSION['step1_data'] : ''; ?>">
    <input type="text" name="step2_field" value="<?php echo isset($_SESSION['step2_data']) ? $_SESSION['step2_data'] : ''; ?>">
    <button type="submit">Next</button>
    <button type="submit" name="back_button">Back</button>
</form>