Deleting a file after user download it

Deleting a file after user download it

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

Stefan Bogdanescu

Founder & Senior Architect

Deleting Files After User Download in PHP

When serving a file to a user, particularly after dynamically generating a ZIP archive on the fly, the immediate instinct is often to delete the source file as soon as the download starts. However, achieving this reliably requires managing the lifecycle of the HTTP request and the state of the connection. A naive approach using unlink() immediately after starting the output with readfile() creates a race condition that leaves your server cluttered with temporary files if the user cancels the download or experiences a timeout.

The core challenge is distinguishing between a successful completion of the transfer and an interrupted session. In PHP, once you begin sending headers and writing to the output buffer, the script must remain alive until the browser confirms it has received the data or explicitly closes the connection. If you delete the file before the user finishes downloading, you might inadvertently corrupt the stream for clients that pause and resume downloads (like Firefox's "Save Page As" or certain mobile browsers) that expect the file to persist during the transfer window.

The most robust solution involves keeping the temporary file open for the duration of the request and deleting it only after the script has finished executing. This ensures that if the browser successfully finishes the download, the file is removed when the script naturally terminates at the end of the request cycle. However, this leaves a specific edge case: what happens when the user hits the "Stop" button or loses their internet connection mid-transfer?

To handle interruptions, you need to detect if the client has disconnected before the script finishes. PHP provides the connection_aborted() function for exactly this purpose. This function returns true if the remote host terminated the TCP/IP connection while the script was running. By wrapping your cleanup logic inside a conditional check for this state, you can ensure the temporary file is removed even in failure scenarios.

Here is how you can implement this pattern safely:

header('Content-type: application/zip');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="file.zip"');

// Ensure we don't exit on client disconnects during output buffering
ignore_user_abort(true); 

$fh = fopen($file, 'r');
if ($fh === false) {
    http_response_code(500);
    die('Unable to read file.');
}

// Stream the file content
stream_copy_to_stream($fh, fopen('php://output', 'rb'));

// Clean up handles
fclose($fh);

// Check for aborted connections before deleting
if (connection_aborted()) {
    unlink($file);
} else {
    // Optionally delete here as well, or rely on script termination
    // unlink($file); 
}

In this implementation, ignore_user_abort(true) is crucial. By default, PHP sends a "Timeout" status code if the client disconnects before the script finishes. Setting this flag prevents that, allowing you to gracefully detect the disconnect via connection_aborted() and clean up resources without triggering an error response to the client.

There are trade-offs to consider with this approach. While it handles interruptions well, it does not account for server-side timeouts (e.g., PHP's max_execution_time or Nginx/Apache proxy timeouts). If the download takes longer than the configured limit, the script will be killed by the web server regardless of whether the user finished downloading. In such high-volume or long-duration scenarios, relying solely on unlink() might not be sufficient to prevent disk space leaks if the script crashes unexpectedly.

For environments where you cannot guarantee immediate cleanup or deal with massive numbers of concurrent users, a scheduled task like a cron job remains a valid fallback strategy. You could run a script every hour to scan and remove any temporary files older than a specific timestamp (e.g., files created in the last 24 hours). This adds a layer of safety against edge cases where PHP crashes silently or memory limits force an abrupt termination before connection_aborted() can be evaluated.

If you are building this within a Laravel application, you might also consider leveraging Laravel's storage features to manage these temporary paths with built-in expiration policies, though the underlying logic for detecting connection drops remains a standard PHP concern.

Our network