Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

php - adding header will not make a file download

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

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

1 Reply

0 votes
by (71.8m points)

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;
}
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...