Write a text file and force to download with php

Write a text file and force to download with php

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

Stefan Bogdanescu

Founder & Senior Architect

Force Browser to Download Text Files in PHP

When you create a file on the server using standard file I/O functions like fopen and fwrite, the browser has no inherent knowledge that this resource should be treated as downloadable content. By default, your web server will likely serve the generated file.txt with a Content-Type header of text/plain. While browsers are generally forgiving and may attempt to render plain text directly in the window, this behavior is inconsistent across different user agents and can lead to poor user experience if you intend for the file to be saved locally.

To reliably trigger a download dialog or force the browser to save the file rather than open it inline, you must manipulate the HTTP response headers before sending any output. The two critical headers are Content-Type and Content-Disposition.

Setting the Content-Disposition Header

The primary mechanism for controlling whether a file opens in the browser or prompts a download is the Content-Disposition header. You set this using PHP's header() function before any characters are written to the output buffer, including whitespace.

To force a download, you need to set the disposition to attachment. This tells the client that the resource should be treated as an attachment rather than part of the document body. Additionally, it is best practice to specify the filename using the filename parameter so the browser knows what to name the file on the user's disk.

header('Content-Type: text/plain; charset=utf-8');
header('Content-Disposition: attachment; filename="file.txt"');
header('Pragma: public'); // Required for some browsers to handle downloads correctly
header('Expires: 0');     // Tells caching systems not to cache the file indefinitely
header('Cache-Control: must-revalidate, post-check=0, pre-check=0', false);

Once these headers are sent, you can output the content. Instead of writing to a physical file on the disk first with fopen and fwrite, it is more efficient to echo the string directly. This approach eliminates unnecessary disk I/O and reduces the risk of race conditions or permission issues if the user's browser blocks access to the server's filesystem.

echo 'text1.....';
exit();

Why Physical Files Are Often Unnecessary

In your original snippet, you created a physical file on the server:
$handle = fopen("file.txt", "w"); fwrite($handle, "text1....."); fclose($handle);

While this works if you subsequently read that file and echo it, it introduces several drawbacks. First, you are consuming disk space and file system resources for a single request. Second, if the application generates dynamic content based on user input or temporary data, writing to a persistent file path can lead to security vulnerabilities or accidental overwriting of existing files.

By generating the content in memory (or reading from it only when necessary) and piping it directly to the output stream with the correct headers, you ensure that the browser receives exactly what you intend without relying on intermediate disk operations. This is particularly important when handling large datasets; streaming data directly to the client prevents memory exhaustion and keeps CPU usage lower than writing to a temporary file and reading it back into a string buffer.

Handling Browser Variations and Security

Although setting Content-Disposition: attachment is the standard solution, browser behavior can vary. Some older or less common browsers might ignore the header and still attempt to render the content if they detect a text MIME type. In these rare cases, you can include an inline JavaScript prompt in the HTML response, though this is generally considered a fallback rather than a primary strategy.

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="file.txt"');
echo 'text1.....';
exit();

Using application/octet-stream as the Content-Type is another technique often employed for generic file downloads where a specific MIME type isn't defined. This forces most browsers to treat the content as binary data, reinforcing the download behavior. However, for a .txt file, specifying text/plain alongside attachment remains the most semantically correct approach, balancing user accessibility with download intent.

Always ensure that no whitespace or BOM (Byte Order Mark) characters precede your headers. Even a single newline character before the first header() call can cause the headers to be stripped by the web server, resulting in a 500 Internal Server Error or silent failure where the browser simply displays the text without offering a download option.

Our network