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

2

2 Answers 2

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;
?>
6
  • 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, 2012 at 15:17
  • 1
    you cannot force to download 2 files, unless you call them separately from another page ... with iframes! Aug 10, 2012 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 8, 2018 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, 2018 at 18:43
  • Thnx but unable to fetch data in loop. Its showing only single data in txt file. How should I do? May 10, 2019 at 11:01
6
$content = file_get_contents ($filename);
header ('Content-Type: application/octet-stream');
echo $content;

Should work

1
  • 1
    it's better to add header('Content-Disposition: attachment; filename='.basename('file.txt')); also to get proper filename Jan 17, 2020 at 19:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.