How can hidden form fields be utilized in PHP to store and retrieve the previous URL for redirection purposes?

When redirecting users to a different page in PHP, it can be useful to store the previous URL in a hidden form field so that it can be retrieved and used for redirection purposes. This can be achieved by including a hidden input field in the form that captures the current URL before the redirection. Upon submission of the form, the previous URL can be accessed from the hidden form field and used for redirection.

// Store the previous URL in a hidden form field
echo '<form method="post" action="redirect.php">';
echo '<input type="hidden" name="previous_url" value="' . $_SERVER['HTTP_REFERER'] . '">';
echo '<input type="submit" value="Submit">';
echo '</form>';

// In redirect.php, retrieve and use the previous URL for redirection
if(isset($_POST['previous_url'])){
    $previous_url = $_POST['previous_url'];
    header("Location: $previous_url");
    exit();
}