Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

It's pretty well documented that adding a header is the way to make a link downloadable, but I must be doing something wrong. I write the file, and then produce some HTML linking to it, but the file will not download, only appear in the browser.

<?

   //unique id
   $unique = time();

   $test_name = "HTML_for_test_" . $unique . ".txt";

   //I should put the file name I want the header attached to here (?)
   header("Content-disposition: attachment;filename=$test_name");

   $test_handler = fopen($test_name, 'w') or die("no");

   fwrite($test_handler, $test);
   fclose($test_handler);

?>

<a href="<?=$test_name">Download File</a>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
167 views
Welcome To Ask or Share your Answers For Others

1 Answer

Well you are just echoing an HTML tag - you should read the file content instead, like proposed on PHP Doc:

<?php
$file = 'monkey.gif';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...