How can you capture the previous URL when submitting a form in PHP?

When submitting a form in PHP, you may want to capture the previous URL to redirect the user back to the same page after form submission. This can be achieved by storing the previous URL in a session variable before the form is submitted. You can then use this stored URL to redirect the user back to the previous page after the form is processed.

// Start the session
session_start();

// Store the previous URL in a session variable
$_SESSION['previous_url'] = $_SERVER['HTTP_REFERER'];

// Process the form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Your form processing code here
    
    // Redirect the user back to the previous URL
    header('Location: ' . $_SESSION['previous_url']);
    exit;
}