Write a Text File and Force to Download with PHP

Write a text file and force to download with php

use readfile() and application/octet-stream headers

<?php
$handle = fopen("file.txt", "w");
fwrite($handle, "text1.....");
fclose($handle);

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename('file.txt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');
exit;
?>

create, write and download a txt file using php

The correct way to do it would be:

<?php

$file = "test.txt";
$txt = fopen($file, "w") or die("Unable to open file!");
fwrite($txt, "lorem ipsum");
fclose($txt);

header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
header("Content-Type: text/plain");
readfile($file);

?>

Writing string to file and force download in PHP

You do not need to write the string to a file in order to send it to the browser. See the following example, which will prompt your UA to attempt to download a file called "sample.txt" containing the value of $str:

<?php

$str = "Some pseudo-random
text spanning
multiple lines";

header('Content-Disposition: attachment; filename="sample.txt"');
header('Content-Type: text/plain'); # Don't use application/force-download - it's not a real MIME type, and the Content-Disposition header is sufficient
header('Content-Length: ' . strlen($str));
header('Connection: close');

echo $str;

php - How to force download of a file?

You could try something like this:

<?php

// Locate.
$file_name = 'file.avi';
$file_url = 'http://www.myremoteserver.com/' . $file_name;

// Configure.
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$file_name."\"");

// Actual download.
readfile($file_url);

// Finally, just to be sure that remaining script does not output anything.
exit;

I just tested it and it works for me.

Please note that for readfile to be able to read a remote url, you need to have your fopen_wrappers enabled.

Creating and Downloading a file using PHP

First, as Harke told, you redirect (or link) to a script that only takes care of offering the download, you can go around that easily

clean the output buffer before read file and exit the script after readfile

ob_clean();
flush();
readfile($file);
exit;


Related Topics



Leave a reply



Submit