25

Im using a button to direct to a script which creates a text file:

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

after that I want the web browser to propose to download or open this file how should I do? Thanks

stevey
  • 1,137
  • 4
  • 21
  • 30

2 Answers2

52

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;
?>
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107
  • Thx I've tried it works but if I want the web browser to propose to download 2 files how should I do? – stevey Aug 10 '12 at 15:17
  • 1
    you cannot force to download 2 files, unless you call them separately from another page ... with iframes! – Mihai Iorga Aug 10 '12 at 17:55
  • It was necessary for me to change my handle: $handle = fopen("php://output", "w"); Also, it seemed that fwrite wasn't overwriting anything, so I had to call ob_end_clean() – Ghoti Feb 08 '18 at 20:40
  • To note that if you are using ajax (dataType: 'json') to post data and call the PHP file, the content of the text file will be returned as text regardless what you put in your PHP code. – Adrian P. Feb 27 '18 at 18:43
  • Thnx but unable to fetch data in loop. Its showing only single data in txt file. How should I do? – phpforcoders May 10 '19 at 11:01
  • @MihaiIorga I am outputting in .rtf format. Could I change my font-family? – Mithun Jack May 12 '20 at 14:09
6
$content = file_get_contents ($filename);
header ('Content-Type: application/octet-stream');
echo $content;

Should work

Edson Medina
  • 9,862
  • 3
  • 40
  • 51