PHP header() redirect with POST variables

PHP header() redirect with POST variables

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

PHP header() redirect with POST variables

When handling form submissions in PHP, a common pattern involves validating data and conditionally redirecting users. If validation passes, you might send them to a success page (posted.php). However, when validation fails, the goal is often to return the user to the original form (form.php) so they can correct their input without losing the data they just typed. The challenge arises because standard HTTP redirects using header('Location: ...') discard the body of the request. Since HTML forms submit via POST and the server discards the payload after processing, retrieving those specific variables on a redirect to a previous page is impossible without an intermediary storage mechanism.

The core issue lies in the stateless nature of the HTTP protocol. Once action.php executes header('Location: ...'), the browser makes a new request to that URL. That new request contains no knowledge of the POST data sent to action.php. You cannot append $_POST['one'] to the URL, and you generally should not use GET parameters for large datasets due to URL length limits and security concerns regarding sensitive data exposure in logs or browser history.

If you explicitly exclude session usage as a constraint, the solution relies on server-side storage that persists beyond the single request lifecycle but does not require the client state management of sessions. The most direct approach is utilizing a temporary file or database row to act as a buffer. When action.php encounters an error, it saves the relevant POST variables to this temporary store and then issues the redirect. Upon reaching the original form page, the script checks for this temporary data and repopulates the inputs before cleaning up the storage.

Here is how that logic translates into code within action.php. You must ensure the headers are sent immediately after deciding to redirect, before any output or error messages:

// action.php
$errors = [];

if (!empty($_POST)) {
    // Simulated error check
    if (error_check($_POST['one'])) {
        $errors[] = "Invalid input for 'one'";
        
        // Save the POST data to a temporary location
        // Using a file is simple and does not require database overhead or session handling
        $tempFile = sys_get_temp_dir() . '/form_buffer_' . bin2hex(random_bytes(4)) . '.txt';
        
        $dataToSave = [
            'one' => $_POST['one'],
            'two' => $_POST['two'],
            'three' => $_POST['three']
        ];
        
        file_put_contents($tempFile, json_encode($dataToSave));

        // Redirect back to the form
        header('Location: form.php');
        exit;
    } else {
        // Success logic here
        // ...
    }
}

In this implementation, we serialize the $_POST array into a JSON string and write it to a uniquely named temporary file. Using bin2hex(random_bytes(4)) ensures the filename is unique per request, preventing collisions if multiple users submit forms simultaneously. This approach avoids the overhead of initializing a session, which involves hashing data and managing cookies, and bypasses the limitations of URL parameters.

On the receiving end, form.php, you need to check for this temporary file before rendering the form. If it exists, you decode the JSON and assign those values to your input fields:

// form.php
$tempFile = sys_get_temp_dir() . '/form_buffer_' . bin2hex(random_bytes(4)) . '.txt';

if (file_exists($tempFile) && is_readable($tempFile)) {
    $savedData = json_decode(file_get_contents($tempFile), true);
    
    // Populate fields safely, assuming non-empty data
    if ($savedData['one'] !== null) $_POST['one'] = $savedData['one'];
    if ($savedData['two'] !== null) $_POST['two'] = $savedData['two'];
    if ($savedData['three'] !== null) $_POST['three'] = $savedData['three'];
}

// Render the form using htmlspecialchars for user input
?>
<form name="example" action="action.php" method="POST">
  <input type="text" name="one" value="<?= htmlspecialchars($_POST['one'] ?? '') ?>">
  <input type="text" name="two" value="<?= htmlspecialchars($_POST['two'] ?? '') ?>">
  <input type="text" name="three" value="<?= htmlspecialchars($_POST['three'] ?? '') ?>">
  <input type="submit" value="Submit!">
</form>

<?php 
// Clean up the temporary file after reading
if (file_exists($tempFile)) {
    unlink($tempFile);
}
?>

This pattern effectively mimics a session for specific variables without invoking the session_start() function. It keeps the implementation lightweight and strictly server-side. However, developers must be mindful of the temporary directory's configuration; ensure that the web server user has write permissions to sys_get_temp_dir(). Additionally, always clean up these files immediately after reading to prevent disk space leaks and security issues where sensitive data might linger if the script crashes unexpectedly.

While frameworks often abstract this away using Flash messages or session attributes, understanding the underlying mechanics allows you to solve constraints like "no sessions" with minimal footprint. For larger projects or when dealing with complex state management in PHP, exploring robust solutions provided by modern ecosystems can simplify these manual buffering tasks. Resources like https://laravelcompany.com discuss how frameworks manage state and redirects elegantly, but for legacy scripts or constrained environments, this file-based buffer is a reliable, dependency-free solution.

Our network