我是一名新的PHP程序员。我正在尝试编写代码以允许用户从我的网站下载文本文件。我按照关于这个主题的类似问题的答案,并将以下测试程序放在一起。它没有强制下载转到文件,而是将内容发送到屏幕(在Chrome,IE,Firefox中)。有人能指出我做错了吗?
这是我的测试代码:
<?php
$file = "test.txt";
if(!file_exists($file)) die("I'm sorry, the file doesn't seem to exist.");
$type = filetype($file);
// Send file headers
header("Content-type: $type");
header("Content-Disposition: attachment;filename=\"test.txt\"");
header("Content-Transfer-Encoding: binary");
header('Pragma: no-cache');
header('Expires: 0');
// Send the file contents.
set_time_limit(0);
readfile($file);
exit();
?>
答案 0 :(得分:0)
您只需使用
即可$handle = fopen("file.txt", "w");
fwrite($handle, "Shadow ");
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;
编辑,在单个php页面上尝试。
答案 1 :(得分:0)
此代码将在屏幕上显示文本文件内容,用户可以将其下载为文本普通文件:
$file = "test.txt";
if(!file_exists($file)) die("I'm sorry, the file doesn't seem to exist.");
$type = filetype($file);
// Send file headers
header("Content-type: $type");
header('Pragma: no-cache');
header('Expires: 0');
// Send the file contents.
set_time_limit(0);
echo file_get_contents($file);
但是这段代码(由@Drop Shadow提供)会强制浏览器显示下载对话框而不显示任何内容:
$file = "test.txt";
if(!file_exists($file)) die("I'm sorry, the file doesn't seem to exist.");
$type = filetype($file);
// Send file headers
header("Content-type: $type");
header("Content-Disposition: attachment;filename=\"test.txt\"");
header("Content-Transfer-Encoding: binary");
header('Pragma: no-cache');
header('Expires: 0');
// Send the file contents.
set_time_limit(0);
readfile($file);
exit();