添加头不会下载文件


adding header will not make a file download

添加标题是使链接可下载的方法,这一点已经得到了很好的证明,但我一定做错了什么。我写了这个文件,然后生成一些HTML链接到它,但这个文件不会下载,只会出现在浏览器中。

<?
   //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>

好吧,你只是在回显一个HTML标记——你应该读取文件内容,就像在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;
}
?>

经过大量测试,这是我提出的组合,从那以后,它在我的所有项目中都起了作用。

处理下载请求的程序

 <?php
// Do all neccessary security checks etc to make sure the user is allowed to download the file, etc..
// 
 $file = '/path/to/your/storage/directory' . 'the_stored_filename';
 $filesize = filesize($file);
 header('Content-Description: File Transfer');
 header("Content-type: application/forcedownload");
 header("Content-disposition: attachment; filename='"filename_to_display.example'"");
 header("Content-Transfer-Encoding: Binary");
 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
 header('Pragma: public');
 header("Content-length: ".$filesize);
 ob_clean();
 flush();
 readfile("$file");
 exit;

编辑

上面的代码会进入它自己的文件,例如"download.php"。然后你会将另一个页面上的下载链接更改为类似的内容:

 <a href="download.php?filename=<?php echo $test_name; ?>">Download File</a>

您还需要修改上面的php代码,以便它在您的情况下工作。在我刚刚给你的例子中,你会想改变这一行:

  $file = '/path/to/your/storage/directory' . 'the_stored_filename';

对此:

  $file = $_get['filename'];

将在最基本的水平上工作。在任何生产环境中盲目使用$_get["文件名"]之前,您都需要对其值进行净化。

如果你想在用户请求的同一页面上显示下载,那么看看我对这篇文章的回答:从javascript 下载多个PDF文件