PHP generate file for download then redirect

PHP generate file for download then redirect

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

Stefan Bogdanescu

Founder & Senior Architect

The HTTP Reality of Generating Files and Redirecting

You have a PHP script that successfully streams a CSV file to the browser using Content-Disposition: attachment. You then attempt to append a redirect header to send the user to a post-download page, but the browser simply ignores the Location header. This isn't a bug in your logic; it is a fundamental constraint of how HTTP works regarding request lifecycles.

When you echo file content directly to the output stream before issuing a redirect, you have already committed the transaction. The client (the browser) receives the response body—the CSV data—and marks the current operation as complete. At this point, the server has no authority to change the URL of the resource being rendered. Adding header("Location: /newpage") after the file output is functionally equivalent to shouting orders at a car that has already crossed the finish line; the client will render the content it received and ignore any subsequent redirection instructions.

To solve this, you must decouple the file generation from the redirect logic. The standard architectural pattern is to separate the "heavy" task of creating the file from the user interaction flow. Instead of streaming the file inline within a single request that ends with a redirect, you should store the generated file in temporary server storage and provide a distinct endpoint for downloading it.

Here is how to restructure the code. First, modify your generation script to write the CSV content to a temporary file on the disk rather than echoing it immediately. You can use PHP's tempnam() function to create a unique, safe filename in a system temp directory:

$tempFile = tempnam(sys_get_temp_dir(), 'CSV');

// Generate $content and save to $tempFile
file_put_contents($tempFile, $content);

// Store the path or metadata in your database/session for later retrieval
// For example, set a session variable with the filename and expiration time
$_SESSION['download_file'] = $tempFile;
$_SESSION['download_expires'] = time() + 300; // Clean up after 5 minutes

// Redirect immediately to the next step
header("Location: /newpage");
exit();

In this approach, the user's browser never receives a response containing both the file and a redirect. Instead, the script performs the write operation, updates state (potentially in the database or session), and issues a clean redirect. The actual download happens asynchronously when the user navigates to the specific download URL.

This pattern requires a second endpoint to handle the actual file delivery. This route should verify that the request is authorized, check if the temporary file still exists, and then serve it using the Content-Disposition header as you originally intended.

// In your /download.php route
if (!isset($_GET['file_path'])) {
    http_response_code(404);
    exit('No file specified.');
}

$filePath = $_GET['file_path'];
if (!file_exists($filePath) || !is_file($filePath)) {
    // Handle cleanup and error
    unlink($filePath);
    http_response_code(404);
    exit('File not found or expired.');
}

// Serve the file
header('Content-Type: application/csv');
header('Content-Length: ' . filesize($filePath));
header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');

readfile($filePath);
unlink($filePath); // Optional: delete immediately after serving
exit();

There are trade-offs to consider with this method. It introduces an extra round-trip for the user if they need to download multiple files, as each requires a separate request to the download endpoint. However, it ensures that the redirect mechanism works reliably and prevents memory exhaustion in scripts that generate massive CSVs, since file_put_contents streams data to disk rather than loading the entire dataset into RAM before sending.

If you are working within the Laravel framework, this pattern aligns well with its event-driven architecture. You can trigger a job that generates the file asynchronously, store the path in the database, and redirect the user while waiting for the job to complete, or simply set up a scheduled task to clean up old temporary files automatically.

The core principle remains: you cannot redirect after sending output. By offloading the file serving to a dedicated endpoint and managing the lifecycle of the file separately, you regain full control over the user flow and ensure the download prompt appears exactly when intended.

Our network