create, write and download a txt file using php

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

header("Content-Disposition: attachment; filename=\"" . basename($file) . "\"");
header("Content-Type: application/force-download");
header("Content-Length: " . filesize($file));
header("Connection: close");

File is created/open and writen but it is not downloaded.

Any help?

4 Answers

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);

?>

You need to output something in order to let the user download a file. Try this code:

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

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="FILENAME"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: test.txt');
ob_clean();
flush();
readfile('text.txt');
exit();

Change FILENAME with the name of the file you want the user to download.

After you created a file, you should output it's contents to browser, for example with fpassthru, as you use file handler:

$path = "test.txt";
$file = fopen($path, "w") or die("Unable to open file!");
fwrite($file, "lorem ipsum");
//fclose($file); // do not close the file
rewind($file);   // reset file pointer so as output file from the beginning

// `basename` and `filesize` accept path to file, not file descriptor
header("Content-Disposition: attachment; filename=\"" . basename($path) . "\"");
header("Content-Type: application/force-download");
header("Content-Length: " . filesize($path));
header("Connection: close");
fpassthru($file);
exit();

I think you only need content for the download process

<?PHP

//config
$namefile = "test.txt";
$content = "lorem ipsum";

//save file
$file = fopen($namefile, "w") or die("Unable to open file!");
fwrite($file, $content);
fclose($file);

//header download
header("Content-Disposition: attachment; filename=\"" . $namefile . "\"");
header("Content-Type: application/force-download");
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header("Content-Type: text/plain");

echo $content;

thank you.

Related