【问题标题】:text file download code in phpphp中的文本文件下载代码
【发布时间】:2015-08-23 05:50:16
【问题描述】:

我是一名新的 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();

?>

【问题讨论】:

  • 测试代码没有出现。我会再试一次:
  • 您的问题下方有一个“编辑”链接。您可以单击它并将缺少的代码添加到问题中,而不是添加评论。

标签: php file download


【解决方案1】:

你可以简单地使用

$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 页面上尝试。

【讨论】:

  • 感谢您的回复。我尝试了这个建议,但内容仍然出现在屏幕上。还有什么问题?
  • 它工作正常。在单个 php 页面上尝试此操作,然后您可以了解您还有另一个问题。
  • 我只是复制您的代码并在 Chrome 44.0.... 和 IE11 上运行它。两人都进入了屏幕。是的,我确实有另一个问题,但我不知所措。你有什么建议吗?
【解决方案2】:

此代码将在屏幕上显示文本文件内容,用户可以将其下载为纯文本文件:

$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();

【讨论】:

  • Drop Shadow 的 PHP 代码应该可以工作,但我怀疑我的系统存在其他问题,导致输出缓冲区没有将其发送到文件,而只是显示在屏幕上。我不知道,我希望有人可以提出一些建议。
猜你喜欢
  • 2011-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-21
  • 2017-10-30
  • 2012-05-19
  • 2013-07-21
相关资源
最近更新 更多